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格式的數據。
@ will2m已更新。我的錯。 – DhruvJoshi
非常感謝你 - 我不敢相信我沒有想到插入...執行的變量 - 嗯 – wl2m
所有的時間都會發生!開發人員的塊:) – DhruvJoshi