首先,您需要拆分该字符串。这是一个可行的拆分功能:
Create Function [dbo].[split]
(@input varChar(8000) -- List of delimited items
,@delimit varChar(8000) = ',') -- delimiter that separates items
Returns @List Table ([item] varChar(8000)) As
Begin
Declare @item VarChar(8000);
while charIndex(@delimit, @input, 0) <> 0 Begin
Select
@item = rTrim(lTrim(subString(@input, 1, charIndex(@delimit, @input, 0) - 1))),
@input = rTrim(lTrim(subString(@input, charIndex(@delimit, @input, 0) + Len(@delimit), Len(@input))));
If Len(@item) > 0 Insert Into @List Select @item
End
If Len(@input) > 0 Insert Into @List Select @input
Return;
End
然后,您需要将这些值加入您的国家/地区表中,然后重新加入它们。这将使您获得最大的收益:
Select ID
,[Name] as [User]
,(
Select [country] + ', '
From [Countries]
Where [ID] In (
Select Cast([item] As Integer)
From dbo.split(U.Countries, ',')
Where IsNumeric(item) = 1)
Order By [country]
For XML Path('')) As [CountriesByName]
From [Users] As U
但是,这会留下一个逗号。您可能想在其他层上删除它,但以防万一您必须在 SQL 中执行此操作,这应该可以:
Select ID
,[User]
,Left([CountriesByName], Len([CountriesByName]) - 1) As [CountriesByName]
From (
Select ID
,[Name] as [User]
,(
Select [country] + ', '
From [Countries]
Where [ID] In (
Select Cast([item] As Integer)
From dbo.split(U.Countries, ',')
Where IsNumeric(item) = 1)
Order By [country]
For XML Path('')) As [CountriesByName]
From [Users] As U) As [Results]