T-SQL對(duì)字符串的處理能力比較弱,比如我要循環(huán)遍歷象1,2,3,4,5這樣的字符串,如果用數(shù)組的話,遍歷很簡(jiǎn)單,
但是T-SQL不支持?jǐn)?shù)組,所以處理下來(lái)比較麻煩。下邊的函數(shù),實(shí)現(xiàn)了象數(shù)組一樣去處理字符串。用臨時(shí)表作為數(shù)組:
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
?
-----------執(zhí)行
?
select ? * ? from ? dbo.F_Limitsplit('1,2,3,4,5,6,7',1) ??
????
--------------------執(zhí)行結(jié)果
UserID?????ID
1 1
1 2
1 3
1 4
1 5
1 6
1 7
?
?
=====================================================
數(shù)據(jù)
id???data
1????a
1????b
1????c
2????aa
2????bb
結(jié)果:?
1?abc
2?aabb
就是要把data?列多行合并成一行顯示
要求:一句sql語(yǔ)句.?不能用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
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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