2016-03-09 179 views
1

如何將返回列轉換爲逗號分隔字符串?我想要使​​用@sql,但必須手動鍵入值。sql將列值轉換爲逗號分隔字符串

declare @orderId as int, @sql AS VARCHAR(MAX) 
set @orderId = 10 
set @sql = 'select orderId, categoryId, itemId from Orders where orderId = ' + CONVERT(varchar(10), @orderId) 
--select @sql as 'sql stmt' --select orderId, categoryId, itemId from Orders where orderId = 10 
--execute(@sql) 
--will return as: 
--orderId categoryId itemId 
--10 281 1054 
declare @dt table(orderId varchar(10), categoryId varchar(10), itemId varchar(10)) 
--insert @dt values (@sql) 
insert @dt values ('10','281','1054') -- did this to get results but want to use @sql 
--how to get the @sql to be a string as '10','281','1054' 
select '{"orderinfo" : [' + STUFF((
    select 
     ',{"Order Id":' + orderId 
     + ',"Category Id":' + categoryId 
     + ',"Item Id":' + itemId 
     +'}' 

    from @dt 
    for xml path(''), type 
).value('.', 'varchar(max)'), 1, 1, '') + ']}' as jsonData 
--end results: {"orderinfo" : [{"Order Id":10,"Category Id":281,"Item Id":1054}]} 

我最感興趣的是返回json格式的數據。

回答

0
declare @orderId as int, @sql AS VARCHAR(MAX) 
set @orderId = 10 
set @sql = 'select orderId, categoryId, itemId from Orders where orderId = ' + CONVERT(varchar(10), @orderId) 

declare @dt table(orderId varchar(10), categoryId varchar(10), itemId varchar(10)) 


insert into @dt exec(@sql) 
-- this is what you needed 


select '{"orderinfo" : [' + STUFF((
    select 
     ',{"Order Id":' + orderId 
     + ',"Category Id":' + categoryId 
     + ',"Item Id":' + itemId 
     +'}' 

    from @dt 
    for xml path(''), type 
).value('.', 'varchar(max)'), 1, 1, '') + ']}' as jsonData 
--end results: {"orderinfo" : [{"Order Id":10,"Category Id":281,"Item Id":1054}]} 
+0

@ will2m已更新。我的錯。 – DhruvJoshi

+0

非常感謝你 - 我不敢相信我沒有想到插入...執行的變量 - 嗯 – wl2m

+0

所有的時間都會發生!開發人員的塊:) – DhruvJoshi

0

我建議您創建一個標量函數,該函數使用獲取並生成描述字符串的遊標。

然後在選擇查詢時調用你的函數。

相關問題