T-SQL對字符串的處理能力比較弱,比如我要循環遍歷象1,2,3,4,5這樣的字符串,如果用數組的話,遍歷很簡單,
但是T-SQL不支持數組,所以處理下來比較麻煩。下邊的函數,實現了象數組一樣去處理字符串。用臨時表作為數組:
ALTER function [dbo].[F_Limitsplit](@IDs varchar(max),@UserID int)
returns @t table(UserID int,ID int)
as
begin
while(charindex(',',@IDs)<>0)
begin
insert @t(UserID,ID) values (@UserID,substring(@IDs,1,charindex(',',@IDs)-1))
set @IDs = stuff(@IDs,1,charindex(',',@IDs),'')
end
insert @t(UserID,ID) values (@UserID,@IDs)
return
end
?
-----------執行
?
select ? * ? from ? dbo.F_Limitsplit('1,2,3,4,5,6,7',1) ??
????
--------------------執行結果
UserID?????ID
1 1
1 2
1 3
1 4
1 5
1 6
1 7
?
?
=====================================================
數據
id???data
1????a
1????b
1????c
2????aa
2????bb
結果:?
1?abc
2?aabb
就是要把data?列多行合并成一行顯示
要求:一句sql語句.?不能用sp.
-----------------------------
SQL?codecreate?table?tb(id?int,?data?varchar(10))
insert?into?tb?values(1?,???'a')?
insert?into?tb?values(1?,???'b')?
insert?into?tb?values(1?,???'c')?
insert?into?tb?values(2?,???'aa')?
insert?into?tb?values(2?,???'bb')?
go
select?id,?[data]=replace((select?','+[data]?from?tb?t?where?id=tb.id?for?xml?path('')),',','')
from?tb
group?by?id
drop?table?tb
--------------------------------------------
SELECT O.*,
ItemName=(select ProductName+',' from Bms_OrderGoodsDetail OGD
left join Bms_Products P on OGD.ProductID=P.ProductID
where OGD.OrderGoodsID= O.OrderGoodsID for xml path(''))
FROM [dbo].[Bms_OrderGoods] O
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
