回答

收藏

存储过程中的排序规则冲突

技术问答 技术问答 253 人阅读 | 0 人回复 | 2023-09-12

我的存储过程在执行时抛出错误:4 y: ^2 [) D& @$ j
- Y2 O! V& k( V$ `8 g
错误:无法创建分隔的文本文件(原因:无法进行从varchar值到varchar的隐式转换,因为在UNION ALL运算符中,由于“) z! r* A* x" D1 R5 Y8 o) O- S
Latin1_General_CI_AI”和“
, _1 t4 b8 J! d3 ZLatin1_General_100_CI_AS_KS_SC”之间的排序规则冲突,导致无法解析该值的排序规则。)$ Q5 x' N) l  K5 M

2 k8 I( F$ d9 N我的存储过程基本上会创建一个带分隔符的文件,并将表或视图与文件名一起作为输入。% F1 L* }7 S1 k
我知道这是排序规则问题,但是我尝试在查询中放置Collate Database_Default和Collate
7 h  I7 Z/ b5 O+ |Catalog_Default,但是该错误无法解决。: L+ C% T# x' d* P* w
有人能指导我做错什么吗?: [9 v/ y; I8 k
ALTER PROCEDURE Usp_Delfile
6 L( Z- Y6 E9 ~  k     (@Source VARCHAR(MAX),& U; b$ v  h3 J
      @DestinationFile VARCHAR(MAX),( \% L( c! M! z; J: G
      @ColumnList VARCHAR(MAX) = '',7 g; O& |1 ]& o1 [1 \, E
      @Delimiter VARCHAR(256) = ',',
. a4 M9 ~! h" c      @Qualifier VARCHAR(256) = '"',* m$ u+ S/ }& a3 f
      @Criteria VARCHAR(MAX) = '',
6 E( n: s9 ^. g5 V$ Z      @FirstRow INT = 0,4 G$ l5 P( d! x" L9 C
      @LastRow INT = 0,
+ t+ ]+ Q! d5 G0 P      @Username VARCHAR(256) = '',
3 W9 ^# g& @. y6 a1 f+ m5 W- o& T      @Password VARCHAR(256) = '',& n4 ^. o$ i1 C1 _$ ]0 m
      @Server VARCHAR(256) = '',
/ q0 b( F  A3 O* g- y' e) e      @SourceType VARCHAR(100) = '',/ K5 O* v2 x" B) s5 m
      @SourceTableName VARCHAR(128) = '',9 J+ d7 F: A/ U6 Y- u
      @OtherConnection VARCHAR(MAX) = ''). `  |$ S+ r& m. D. W$ t
AS
$ ?) W+ n* g  E/ e9 fBEGIN+ I4 p8 A# |9 C' V7 b. B
    -- Declare variable5 m! O* D, _4 X# ?
    DECLARE @HeaderCount INT
0 D: P4 Q* u, {& x$ p! v3 e+ }    DECLARE @Header VARCHAR(MAX)
! Y0 D0 X/ H& u" r8 X    DECLARE @SQL VARCHAR(MAX): c8 N6 f/ R* F2 F4 N! t
    DECLARE @COLNAME VARCHAR(MAX)
3 W& e; u& a3 i' ]* r    DECLARE @SUBSQL VARCHAR(MAX)4 k4 V: _8 o! q2 q% [* }2 a. F
    DECLARE @TEMPVIEWNAME VARCHAR(MAX)  D) q8 w7 @2 s7 T
    DECLARE @counter INT
1 @# }# i- K3 U( T    -- Otherconnection is not used but kept for future development7 J% }' r$ }4 x1 d
    SET @OtherConnection = ''6 y+ V5 V8 P9 l5 x" p; d; k
    -- Set the name of the temporary view% g$ `6 e$ J; {% q' K
    SET @TEMPVIEWNAME = 'uTEMPVIEW'+convert(varchar(max),newid())9 z  M8 M4 G% K& q9 p
BEGIN TRY1 A0 e1 y0 Z2 F  L" A! w
    -- Try to figure out the source type in case one is not given and it appears something other than SQL may be given
9 [7 n4 G8 h2 S% Z% t" }    BEGIN TRY6 D6 X5 F& U) f) S1 s6 p
    IF (charindex('\',@SOURCE) > 0 AND charindex('.', reverse(@SOURCE)) = 4 AND @SourceType='')
! h+ e/ ~! C; o( i4 L: T" _0 Y    BEGIN0 A# u- E  \% j9 v# [
        SET @SourceType = SUBSTRING(UPPER(@SOURCE),LEN(@SOURCE)-2,3)/ U! V) O0 K: G4 W
    END% @# F% {! O5 d4 v4 S$ M7 I0 A
    ELSE, d7 d  A& X; }! @3 N/ _" ?6 I
        SET @SourceType = 'SQL'* V8 x! j6 s- |8 E
end try
2 F7 n4 M1 R5 K! _! M* qbegin catch2 |0 B: `# Q7 k! F+ R5 ?, k
-- If an error occurs during this time, ignore it and assume SQL source type. J2 K: r: H7 t
  SET @SourceType = 'SQL'; `2 Y# W0 `; ^$ S- x
end catch9 j; W9 u- y7 t* y$ b

+ j: p$ X* q. M' v7 U1 VIF (UPPER(@SourceType)  'SQL')- m0 _) d5 z+ Y8 S+ g
BEGIN
% y" @) Z4 M: S: J  IF (@OtherConnection  '')% e, A% s2 h9 D, b& J- K
    -- This will be used in the future but disabled for now from previous set statement (I left this in here because I have a horrible memory!)
- @1 [0 h: K; q  v! z0 ^    exec ('create view ['+@TEMPVIEWNAME+'-other] as (select * from OpenRowset('+@OtherConnection+'))')9 B, g' n- N9 [9 i! X
  ELSE
, E+ H) z+ ?0 x0 g) D  BEGIN
! M; ]# G; n% Q    -- If the source is a delimited file, create a view to the file
& g. u; L. D4 L7 R5 }    DECLARE @filepath varchar(256)
; J+ n7 q- k  e3 b4 Y: k4 A9 H" e    DECLARE @filename varchar(256)+ K3 a% S" u. R/ A% X5 F  }6 P- z) t
    DECLARE @OtherViewSQL varchar(max)# B% h- x0 F9 M# A
    -- Get the file path and filename! h. a$ E1 \* v: A
    select @filepath=reverse(substring(reverse(@Source), charindex('\', reverse(@Source))+1, len(@Source) - charindex('\', reverse(@Source)) ))
7 N6 R; `8 t8 ~$ p# ]; y3 ~( |    select @filename=reverse(substring(reverse(@Source), 0, charindex('\', reverse(@Source)) ))! u1 W, J  X1 ], Z% F6 X
    -- Create view to the file using its connector
+ f2 n. D7 V. F    If(UPPER(@SourceType) = 'DELIMITED' OR UPPER(@SourceType) = 'CSV' OR Upper(@SourceType) = 'TEXT' OR Upper(@SourceType) = 'TXT'): Z& q: `& O/ ?5 o$ m
    exec('create view ['+@TEMPVIEWNAME+'-other] as (select * from OpenRowset(''MSDASQL'', ''Driver={Microsoft Text Driver (*.txt; *.csv)};DefaultDir='+@filepath+';'',''select * from ['+@filename+']''))')
% O$ B% _3 a' H+ q' Q    else if(UPPER(@SourceType) = 'DBF' OR UPPER(@SourceType) = 'DBASE' OR UPPER(@SourceType) = 'DBASE3' OR UPPER(@SourceType) = 'DBASEIII' OR UPPER(@SourceType) = 'DBASE 3' OR UPPER(@SourceType) = 'DBASE III' OR UPPER(@SourceType) = 'FOXPRO')6 t0 i5 M9 [5 Y# m
    exec('create view ['+@TEMPVIEWNAME+'-other] as (select * from OpenRowset(''MSDASQL'', ''Driver={Microsoft dBase Driver (*.dbf)};DBQ='+@filepath+';'',''select * from ['+@filename+']''))')
9 S. {  p% F$ v# I% i. K3 j5 |    else IF(UPPER(@SourceType) = 'ACCESS' OR UPPER(@SourceType) = 'MDB')% o2 I$ G) G" s1 U  m, }' s( k
    exec('create view ['+@TEMPVIEWNAME+'-other] as (select * from OpenRowset(''MICROSOFT.JET.OLEDB.4.0'', '''+@filepath+'\'+@filename+''' ;;,['+@SourceTableName+']))')
- r! h1 f: N8 o/ P7 Y% c8 \4 W    else IF(UPPER(@SourceType) = 'EXCEL' OR UPPER(@SourceType) = 'XLS')
. u% `5 u3 b/ ]% X( l    exec('create view ['+@TEMPVIEWNAME+'-other] as (select * from OpenRowset(''MICROSOFT.JET.OLEDB.4.0'', ''Excel 8.0;DATABASE='+@filepath+'\'+@filename+''',''select * from ['+@SourceTableName+'$]''))')0 n2 o3 v9 X1 A+ Y. Y- @5 Y* w
  END& C: |, J: p/ z

7 P4 i" e+ q6 p  @-- Set the source table to the new view9 P- p( K5 ^+ Y. B  C8 c" M2 c; [! v
SET @Source = @TEMPVIEWNAME+'-other'5 m; ?8 I! B- s, J
END
5 z6 m  O0 `' o" z: W2 lELSE
* ~& h1 Q: x2 _  M$ j& I2 q  SET @SourceTableName = @Source% w7 r; B! C( T! F( s- I
-- Check to see if columnlist is provided5 z) P2 Y* r) X$ o3 G
IF (@ColumnList  '')
' m2 U/ K/ u, `. H2 N) Q  BEGIN
# y; F" [, b& |) y" _    -- Get header count from columnlist/ _" c; H* T1 h1 d, C# y
    SELECT @HeaderCount = ((LEN(RTRIM(LTRIM(@ColumnList))) - LEN(REPLACE(RTRIM(LTRIM(@ColumnList)), ',', '')))+1), t: k( l# i& s. [: b* B
    -- Build delimited file header row8 S8 b+ }# n9 b  K: d; U9 y3 Q
    SELECT @Header = COALESCE(@Header  + ',', '') + + T4 ^* ^+ W: o( a. m: b0 {% G
      CASE WHEN @Qualifier = '' THEN ' '''+@Qualifier+'''+CASE when isnumeric(['+column_name+']) = 1 AND
- W7 P9 G( J7 }% s! Y    case when exists(select ordinal_position  from
' l2 u: v# O* O" @/ n  k    INFORMATION_SCHEMA.COLUMNS where Upper(table_name) = '''+Upper((REPLACE(REPLACE(@Source,'[',''),']','')))+'''
0 v. I3 \1 q1 m3 _5 B) `  _/ O' T8 m    and (UPPER(data_type)   ''VARCHAR'' OR UPPER(data_type)   ''NVARCHAR'' OR UPPER(data_type)   ''CHAR'' OR UPPER(data_type)  ''NCHAR'') 9 F7 l6 K' S1 f) H1 w/ I
    and Upper(column_name) ='''+UPPER(column_name) COLLATE CATALOG_DEFAULT +''') THEN -1 ELSE 0
2 Z% p$ {9 g/ ?; V0 j    END = 0
; T) m5 S6 S/ O+ t0 L4 a% w) B; K    THEN cast(cast(['+column_name+']  as decimal(38, 38)) as varchar(max)) ELSE cast(CASE when ['+column_name+']  = '''' THEN NULL ELSE ['+column_name+']  END as varchar(max)) END+'''+@Qualifier+''' as ['+column_name+']'! c" d5 ]. t6 d7 r8 G! H# c) w5 h
    ELSE ' '''+@Qualifier+'''+ISNULL(CASE when isnumeric(['+column_name+']) = 1 AND, k- t- V: G. O& G6 D+ o+ o
    case when exists(select ordinal_position  from
  S5 J& x. r+ n# Z    INFORMATION_SCHEMA.COLUMNS where Upper(table_name)  = '''+Upper((REPLACE(REPLACE(@Source,'[',''),']','')))+''' ; \" m' ]+ N; G+ ~* k
    and (UPPER(data_type)  ''VARCHAR'' OR UPPER(data_type)  ''NVARCHAR'' OR UPPER(data_type)  ''CHAR'' OR UPPER(data_type) ''NCHAR'') , |6 C9 D, G* c. b( x
    and Upper(column_name)='''+UPPER(column_name)+''') THEN -1 ELSE 01 F8 y- G/ }& @) q! A
    END = 0
3 E! i8 ?3 ~+ Z) g    THEN cast(cast(['+column_name+'] as decimal(38, 38)) as varchar(max)) ELSE cast(CASE when ['+column_name+'] = '''' THEN NULL ELSE ['+column_name+'] END as varchar(max)) END,'''')+'''+@Qualifier+''' as ['+column_name+']'( g$ k) O8 G7 d4 V0 ?. M
        END- X& r. {  }* a4 g4 ?$ N
    FROM ( SELECT column_name, rank() OVER (ORDER BY ordinal_position) as rank
+ N2 s. Q& f3 S  S9 ^% Z    FROM INFORMATION_SCHEMA.columns5 T# V5 q- n2 _8 j; w6 l  Q; n
    where UPPER(table_name) = Upper((REPLACE(REPLACE(@Source,'[',''),']',''))) AND charindex(','+column_name+',',RTRIM(LTRIM(','+@ColumnList+','))) > 0
7 P& X% ?. T- N* `    ) t ORDER BY t.rank ASC" _# C  p2 {2 j# K- X" \
    -- Initialize main view query
0 W6 t6 q9 g" I! w* t  h& W    SET @SQL = 'SELECT '0 j4 z- Z2 ]  @& M2 ~
    -- Build main view query
7 K0 w/ h' e0 ]7 E; C    set @counter = 0
/ b8 M( L7 H" I! C) J2 X    while @counter  0' r8 h5 I4 u. q, h- l( l( G
        ORDER BY rank ASC ) as t ORDER BY rank DESC
9 h& O/ C% R: U9 \. e, H5 d  C        -- Add to main view query, Z4 z, e: e" d1 G4 m0 {
        IF @counter = @HeaderCount2 {/ {( V, o+ j- Z
          BEGIN8 W2 J0 c# p! F" s3 H7 {- G0 x" g
            SET @SQL = @SQL + ''''+@Qualifier+'''+ SUBSTRING(RTRIM(LTRIM('''+@ColumnList+''')),charindex('''+@colname+''',RTRIM(LTRIM('''+@ColumnList+'''))), LEN('''+@colname+'''))+'''+@Qualifier+''' as ['+@colname+'] '4 d5 I; B6 H' v7 r2 i+ W  B
          END% H" E3 P2 ^0 Q; H
        ELSE
* ]/ Q  r, e& b: A% y6 w& k5 C          BEGIN
4 M" I% Z) H+ [. \! k            SET @SQL = @SQL + ''''+@Qualifier+'''+ SUBSTRING(RTRIM(LTRIM('''+@ColumnList+''')),charindex('''+@colname+''',RTRIM(LTRIM('''+@ColumnList+'''))), LEN('''+@colname+'''))+'''+@Qualifier+''' as ['+@colname+@Delimiter+'], ') M" A& w/ z* I3 [  u
          END
, v+ n* a0 n$ I* S+ }2 \      end# r5 `! k0 p% p$ w
  END
  ]% ^6 P9 E0 k4 B. N4 {9 T# G. IELSE  f8 G" [* @2 F; K" S
  BEGIN6 O9 r) j; [: z; V7 \9 x8 S
    -- Get header count from columnlist& q- `6 Z3 I" A
    SELECT @HeaderCount = count(column_name)
0 Z% {% W2 f" C  K4 n    FROM INFORMATION_SCHEMA.columns
8 w1 B8 B( U- p% U- B    where UPPER(table_name) = Upper((REPLACE(REPLACE(@Source,'[',''),']','')))
, E7 G+ [9 s- }0 E$ f    -- Build delimited file header row
, b! t+ a& f4 \/ ~  F    SELECT @Header = COALESCE(@Header  + ',', '') +
4 v  I9 h' b2 H" F      CASE WHEN @Qualifier = '' THEN ' '''+@Qualifier+'''+CASE when isnumeric(['+column_name+']) = 1 AND
) O) n4 W6 y& I8 n! x    case when exists(select ordinal_position from
* Q. e( H/ Y$ x. ^$ I    INFORMATION_SCHEMA.COLUMNS where Upper(table_name) COLLATE CATALOG_DEFAULT = '''+Upper((REPLACE(REPLACE(@Source,'[',''),']','')))+'''
4 Y% u) W# G+ g3 B) ^( P5 y    and (UPPER(data_type)  ''VARCHAR'' OR UPPER(data_type)  ''NVARCHAR'' OR UPPER(data_type)  ''CHAR'' OR UPPER(data_type) ''NCHAR'')   d# ?1 P. e. o+ v1 h
    and Upper(column_name)='''+UPPER(column_name)+''') THEN -1 ELSE 03 ?1 \* |* w+ _; A- }3 j  b
    END = 0( N4 P5 P; e0 Q- u7 G+ A, g% o
    THEN cast(cast(['+column_name+'] as decimal(38, 38)) as varchar(max)) ELSE cast(CASE when ['+column_name+'] = '''' THEN NULL ELSE ['+column_name+'] END as varchar(max)) END+'''+@Qualifier+''' as ['+column_name+']'
. U/ c6 R+ {* L# Y/ g# h. U    ELSE ' '''+@Qualifier+'''+ISNULL(CASE when isnumeric(['+column_name+']) = 1 AND . Y# ^$ K  A& x
    case when exists(select ordinal_position from
8 A; d( |; A/ q: E9 q$ s    INFORMATION_SCHEMA.COLUMNS where Upper(table_name) = '''+Upper((REPLACE(REPLACE(@Source,'[',''),']','')))+'''
2 q% N2 b+ q2 u1 N" h$ D# v3 d7 o    and (UPPER(data_type)  ''VARCHAR'' OR UPPER(data_type)  ''NVARCHAR'' OR UPPER(data_type)  ''CHAR'' OR UPPER(data_type) ''NCHAR'')
0 X% b$ `& b6 n0 Z( O4 }    and Upper(column_name)='''+UPPER(column_name)+''') THEN -1 ELSE 0  }' t# I* {& I. a
    END = 01 f! v1 j% r# G* x- {
    THEN cast(cast(['+column_name+'] as decimal(38, 38)) as varchar(max)) ELSE cast(CASE when cast(['+column_name +'] as varchar(max)) = '''' THEN NULL ELSE ['+column_name+'] END as varchar(max)) END,'''')+'''+@Qualifier+''' as ['+column_name+']'( Q. `0 a6 C3 t4 l) ]/ {
    END
+ `5 {: o! a  X  O+ T0 b# G6 f    FROM ( SELECT column_name, rank() OVER (ORDER BY ordinal_position) as rank
+ a" [+ _  y0 d' v4 J5 h; K7 F8 Q9 ~    FROM INFORMATION_SCHEMA.columns( E, H; E6 x/ }
    where UPPER(table_name) = Upper((REPLACE(REPLACE(@Source,'[',''),']','')))
" {( B, p) U% o    ) t ORDER BY t.rank ASC
  w7 O2 h3 K" q2 G' Y. C; [: ~    -- Initialize main view query1 p: _2 p/ w: a% d) J. Y1 s% H
    SET @SQL = 'SELECT '- P% h) P" R5 }2 S
    -- Build main view query* T# J( s, l1 [, t! A* e$ H
    set @counter = 0
* P. N( b0 I5 C8 F0 @    while @counter  '')
) o. z6 P7 M! cBEGIN3 l- C: Y) f* ?
  SET @SQL = @SQL + ' WHERE '+@Criteria+' '3 u  z5 s4 j. u2 O0 v7 P5 E$ F
END
& q3 \  t# L; O& k-- Create temporary view, C/ w9 n% L' g0 v. w9 X
exec('create view ['+@TEMPVIEWNAME+'] as ('+@SQL+')')
  q- d' ?7 e" x: H) [-- Execute bcp on temporary view
0 h8 B& f$ \8 f2 x4 JDECLARE @bcpcmd varchar(8000)7 F, A1 Q1 k4 ~5 i4 C3 A5 @5 G
SET @bcpcmd = 'bcp ["'+db_name()+']..['+@TEMPVIEWNAME+']" out "'+@DestinationFile+'" -k -c ACP -t "'+@Delimiter+'"'
8 R/ k7 c0 F* E$ m+ W4 I-- Add first row and last row arguments to bcp command' q& b* \5 _$ }1 A% x4 U% m- x
IF (@FirstRow > 0)- z- j! ]4 D( Y9 `
SET @bcpcmd = @bcpcmd + ' -F '+cast(@FirstRow as varchar); Y- ^9 p$ h+ `; U* [6 q0 o
IF (@LastRow > 0)) k' T0 m: R, n8 J- {) N2 I
SET @bcpcmd = @bcpcmd + ' -L '+cast(@LastRow as varchar)* s. q7 z* r) q8 [, M- E: t
, X/ g/ X6 ]: |, i: \% r5 \
-- Add server login information0 g6 b1 q# C  L/ W$ ^) |/ _2 L
IF (@Username  '')
1 i& K5 i: J8 c. y  M$ {BEGIN$ [# Z) q' x+ ?9 S8 g+ W  v: H1 d
  SET @bcpcmd = @bcpcmd + ' -U '+@Username
$ M  k! W0 D3 u/ u" w2 q  IF (@Password  ''); u& N& o9 Q1 O
  SET @bcpcmd = @bcpcmd + ' -P '+@Password
5 d6 }4 S$ j3 j: s) W% U* M( uEND; M4 u1 _' D' A; ]+ C
ELSE
2 _' f& t5 h, z# N" VBEGIN
9 K# [& ]+ `5 M  SET @bcpcmd = @bcpcmd + ' -T '
. H- j$ f% k# }2 x+ {END
# I* W0 e' Y' U# n2 g  tIF (@Server  '')
$ j4 U0 K! J' P' ~+ v7 PSET @bcpcmd = @bcpcmd + ' -S '+@Server" S4 i0 B# W; b+ G" w
exec master..xp_cmdshell @bcpcmd5 L/ s# t5 k" O) s# t# V/ r' D
-- Drop temporary view
) |5 ?4 s6 C- Y2 n: t  z* [: `( h& Texec('IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'''+@TEMPVIEWNAME+''')) DROP View ['+@TEMPVIEWNAME+']')9 D0 S7 s* Z0 g% `
exec('IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'''+@TEMPVIEWNAME+'-other'')) DROP VIEW ['+@TEMPVIEWNAME+'-other]')9 `2 S) ~. k2 a0 x4 w- ^
end try9 M. X& O% a/ V% u4 ^/ o5 G( @, l
begin catch2 @8 h- v6 E/ J& A
  -- show error if one occurs
! `; H0 G6 j4 P" A. g: V3 H4 l  SELECT 'ERROR: UNABLE TO CREATE DELIMITED TEXT FILE (Reason:' + error_message() + ')'
6 J1 ~  Y( N+ }$ Z# W6 _5 a  begin try- u4 i4 T" H% R# l
    -- Drop view if an error occurs, w0 f8 Z9 u/ V7 f, `  W
    exec('IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'''+@TEMPVIEWNAME+''')) DROP View ['+@TEMPVIEWNAME+']')5 @% _4 C6 u7 k) k- R& T
    exec('IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'''+@TEMPVIEWNAME+'-other'')) DROP VIEW ['+@TEMPVIEWNAME+'-other]')9 ?1 {+ K, Y& q6 R$ h+ O
  end try
* U, P, o8 M* f1 Z% x  begin catch
7 X& |2 ]9 f6 z! l/ L  end catch( u  b/ x: }7 d! f8 Y
end catch' a: \7 ~# A( S* M, I2 c
END
! n# X9 H2 ^2 |$ {# s5 ?; }                + \/ ]5 ?0 U& o: f  d6 p$ O) z3 e
解决方案:
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则