2015-01-13 40 views
0

我寫了一個存儲過程作爲如何將列中的所有行放入變量?

Declare @Split table 
(
Jurisdiction nvarchar(max) 
) 

Insert into @Split select Jurisdiction from tbLicence where AgentId [email protected]; 

Select * from @Split; 

Declare @products varchar(MAX); 

Select @products = Jurisdiction from @Split; 

Select @products; 

我想把列@Split的所有值@products變量。 請注意,上面的代碼僅將最後一行的列值放在@products中。 請幫助我!

回答

1

首先用empty string初始化變量。然後使用任何分隔符附加所有行。用這個。

DECLARE @products VARCHAR(MAX)=''; 

SELECT @products += Isnull(Jurisdiction, '') + ',' 
FROM @Split; 

SELECT left(@products,len(@products)-1); 

或使用For XML path()

set @products=(select ','+Jurisdiction from @Split for xml path('')) 

select right(@products,len(@products)-1) 
+1

加一。沒有循環的好解決方案:) –

0

這可能會幫助你

Declare @Split table(Jurisdiction nvarchar(max)) 
Declare @products varchar(MAX)='' 
declare @count int=(select count(*) from @split) 
declare @a int=1 

Insert into @Split values ('a'),('b') 


while(@a<@count) 
begin 
    Select @products += Jurisdiction from @Split 
    set @[email protected]+1 

end 

select @products 
0

@Nida ......你可以做到這一點,並使用xml路徑,以及...,但它會串連所有值都用逗號分隔符。我已經通XML路徑做......可能是它會幫助你......在dbo.columnnames

採樣值

Value One 
Value Two 
Value Three 
Value Four 
Value Five 

QUERY

declare @lv_table table(column_values varchar(100)) 
declare @product_v varchar(max) 
insert into @lv_table 
select * from dbo.columnnames 
set @product_v =(

select 
    Stuff(
     (
    SELECT ',' + column_values 
    FROM @lv_table 
    FOR XML PATH('') 
    ), 1, 1, '')) 

    select @product_v 

輸出

Value One,Value Two,Value Three,Value Four,Value Five