使用此功能分割值:
CREATE FUNCTION [dbo].[udfSplitCSV]
(
@String varchar (max),
@Delimiter varchar (10) = ','
)
RETURNS @ValueTable TABLE ([Row] int IDENTITY(1,1), [Value] varchar(max), [Length] int, [Duplicate] int NULL)
BEGIN
DECLARE @NextString varchar(max)
DECLARE @Pos int
DECLARE @NextPos int
IF @String IS NULL RETURN
--Initialize
SET @NextString = ''
SET @String = @String + @Delimiter
--Get position of first Comma
SET @Pos = charindex(@Delimiter,@String)
SET @NextPos = 1
--Loop while there is still a comma in the String
WHILE (@Pos <> 0)
BEGIN
SET @NextString = RTrim(LTrim(SubString(@String,1,@Pos - 1)))
INSERT INTO @ValueTable ([Value], [Length]) VALUES (@NextString, Len(@NextString))
SET @String = SubString(@String,@Pos+1,Len(@String))
SET @NextPos = @Pos
SET @Pos = CharIndex(@Delimiter,@String)
END
UPDATE @ValueTable
SET [Duplicate] = X.Duplicate
FROM @ValueTable VT
INNER JOIN (Select [Row], [Value], Row_Number() OVER (Partition By [Value] ORDER BY [Value], [Row]) as Duplicate FROM @ValueTable) X
ON X.[Row] = VT.[Row]
RETURN
END
-- Select * from dbo.udfSplitCSV('a , c b,c, a', ',')
[Split in SQL]可能的重複(http://stackoverflow.com/questions/2647/split-string-in-sql) – 2013-05-03 08:36:50
在整個過程中使用適當的數據類型會更好。 SQL Server提供了一種用於存儲多個值的類型 - 表。您可以使用[Table-Valued Parameters](http://msdn.microsoft.com/zh-cn/library/bb510489.aspx)將表格數據從客戶端應用程序傳遞到SQL Server,當然,它可以輕鬆地將表格數據結果。 – 2013-05-03 08:36:51