SQL多个逗号分开的字段值 取对应的数据名称信息
字段值
函数实现:
ALTER function [dbo].[GetName](@strs NVARCHAR(500))
RETURNS NVARCHAR(4000)
as
begin
set @strs=','+@strs+','
DECLARE @str1 NVARCHAR(4000)
DECLARE @str2 NVARCHAR(4000)
set @str2=''
declare SyncOrderCursor cursor for
select b.Name from dbo.ShopStore as a
inner join dbo.Shop as b on a.StoreGid=b.Gid
where @strs like '%,'+cast(a.Gid as nvarchar(4000))+',%'
open SyncOrderCursor
fetch next from SyncOrderCursor into @str1
while @@FETCH_STATUS=0
begin
set @str2=@str2+'|'+@str1
fetch next from SyncOrderCursor into @str1
end
close SyncOrderCursor
deallocate SyncOrderCursor
return @str2
End
---另一种实现方式
--select A.Gid,stuff((
-- select '|'+B.Name from Shop B
-- where charindex(','+CAST(B.Gid as varchar(8000))+',',','+ CAST (B.Gid as varchar(8000))+',')>0
-- order by B.Gid
-- for xml path('')
-- ),1,1,'') as name
--from ShopStore A
调用函数实现:
[dbo].GetName(Gids) AS ShopName
|保时捷店铺|奔驰店铺