有成千上萬的關於如何分割/解析字符串的例子。以下是兩個樣本,一個是UDF,另一個是沒有。無論使用CROSS APPLY
隨着UDF
Declare @Yourtable table (FirstName varchar(25) ,LastName varchar(25),userid varchar(25), Regions varchar(50), ViewCosts varchar(25), HelpReviewCosts varchar(25))
Insert Into @Yourtable values
('Darron','Peters','ya00003','All','y','y'),
('John','Davies','ya30982','NA, EM, AP, LA','n','n')
Select A.FirstName
,A.LastName
,A.userid
,Regions =B.RetVal
,A.ViewCosts
,A.HelpReviewCosts
From @Yourtable A
Cross Apply [dbo].[udf-Str-Parse](A.Regions,',') B
沒有一個UDF
Select A.FirstName
,A.LastName
,A.userid
,Regions =B.RetVal
,A.ViewCosts
,A.HelpReviewCosts
From @Yourtable A
Cross Apply (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>'+ replace((Select A.Regions as [*] For XML Path('')),',','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) B
兩個返回
如果需要
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>'+ replace((Select @String as [*] For XML Path('')),@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')
的[SQL服務器分割成CSV多行]可能的複製(http://stackoverflow.com/questions/9811161/sql-server-split-csv-into-multiple-rows) – GurV
爲什麼不修復設計問題呢?使用*分開的*表將人員與地區聯繫起來。你在這裏展示的甚至是第一範式。一旦你有了這個,以你想要的形式檢索數據需要一個簡單的JOIN –
如果你有數據庫模式的控制,你應該規範化數據,而不是存儲一個CSV列表。 –