2011-08-06 50 views
2

我有一個像動態SQL和spexecutesql行爲

c1 c2 c3 c4 
----------------- 
2 1 7 13 
9 2 8 14 
1 3 9 15 
5 4 10 16 
2 5 11 17 
11 6 12 18 

的桌子,一般我不知道列數(代碼@d這裏4)得到一個字符串形式:

2,9,1,5,2,11, 1,2,3,4,5,6, 7,8,9,10,11,12, 13,14,15,16,17,18 

要做到這一點我做:

DECLARE @d INT 
     ,@counterI INT 
     ,@template AS nvarchar(max) 

    SET @d = 4;  
    SET @counterI = 1; 
    Set @template = 'SELECT STUFF( 
         ( SELECT '','' + CAST([col] AS VARCHAR) FROM (';       
    WHILE (@counterI < @d) BEGIN 
     SET @template += ' SELECT [c'+CAST(@counterI-1 AS VARCHAR)+'] AS col FROM [MyTable] UNION ALL '; 
     SET @counterI = @counterI + 1; 
    END 
    Set @template += ' SELECT [c'+CAST(@counterI-1 AS VARCHAR)+'] AS col FROM [MyTable] ' 
    Set @template += ') alldata FOR XML PATH('''') ) , 1 , 1 , '''')';  

declare @CommaString varchar(max) 
set @CommaString = '' 
exec sp_executesql @template, N'@CommaString varchar(max) out', @CommaString out 

所以,如果我做

select @CommaString; 

enter image description here

爲什麼不@CommaString在選擇它返回字符串的那一刻,如果這樣做的sp_executesql的當它打印出來嗎?

+0

你有沒有檢查@template有你期望的我T'你的示例表有第1-4個列,你的SQL看起來像在第0-3列上工作?另外,你在SQL中有兩個不同的表名? – James

+0

對不起,我沒有複製代碼的權利,我已經更新了它,而且,是的,var @ template具有我期望的,事實上,我執行該查詢並給了我字符串,spexecsql部分中的問題產生。 .. – cMinor

回答

3

我可能會遺漏一些關於sp_executesql如何工作的內容,但是你不需要像@template中的'SELECT @CommaString = ...'這樣的東西,以便它將逗號字符串分配給out參數嗎?

只是爲了澄清,我想你需要的東西,如:

DECLARE @d INT 
     ,@counterI INT 
     ,@template AS nvarchar(max) 

SET @d = 4;  
SET @counterI = 1; 
Set @template = 'SELECT @CommaString = STUFF( 
        ( SELECT '','' + CAST([col] AS VARCHAR) FROM (';       
WHILE (@counterI < @d) BEGIN 
    SET @template += ' SELECT [c'+CAST(@counterI-1 AS VARCHAR)+'] AS col FROM [MyTable] UNION ALL '; 
    SET @counterI = @counterI + 1; 
END 
Set @template += ' SELECT [c'+CAST(@counterI-1 AS VARCHAR)+'] AS col FROM [MyTable] ' 
Set @template += ') alldata FOR XML PATH('''') ) , 1 , 1 , '''')';  

declare @CommaString varchar(max) 
set @CommaString = '' 
exec sp_executesql @template, N'@CommaString varchar(max) out', @CommaString = @CommaString out 

作爲一個簡單的例子,這樣的事情也許是更容易閱讀/明白我的意思:

declare @CommaString varchar(max) 
set @CommaString = '' 
exec sp_executesql 'SELECT @CommaString = ''1,2,3''', '@CommaString varchar(max) out', @CommaString = @CommaString out 

順便說一句,我通常看到這種類型的字符串連接:

DECLARE @MyString varchar(max) 

SET @MyString = '' 

SELECT @MyString = @MyString + ',' + MyColumn 
    FROM MyTable 
+0

它假設在行'exec sp_executesql @template,N'@CommaString varchar(max)out',@CommaString out'部分'@CommaString out'完成你所說的,但仍然找不到錯誤... – cMinor

+0

您已經在exec語句中聲明瞭out參數,但@template的內容似乎沒有嘗試設置它? – James

+0

那麼,這就是在exec exec_executesql @template,N'@CommaString varchar(max)out',@CommaString out' aka @template – cMinor