MS SQL 字符拆分存处理
MS SQL Server没有split()函数,但是我们可以写一个Table-valued Functions定义函数[dbo].[udf_SplitStringToTable] :
CREATE FUNCTION [dbo].[udf_SplitStringToTable] ( @string NVARCHAR(MAX), @delimiter CHAR(1) ) RETURNS @result TABLE([ID] INT IDENTITY(1,1),value NVARCHAR(MAX) ) BEGIN DECLARE @start INT, @end INT SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) WHILE @start < LEN(@string) + 1 BEGIN IF @end = 0 SET @end = LEN(@string) + 1 INSERT INTO @result (value) VALUES (SUBSTRING(@string, @start, @end - @start)) SET @start = @end + 1 SET @end = CHARINDEX(@delimiter, @string, @start) END RETURN END
再写另外一个Scalar-valued Function自定义函数[dbo].[udf_SplitString]:
CREATE FUNCTION [dbo].[udf_SplitString] ( @string NVARCHAR(MAX), @delimiter CHAR(1), @index INT ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @rtn NVARCHAR(MAX) SELECT @rtn = [value] FROM [dbo].[udf_SplitStringToTable] (@string,@delimiter) WHERE [ID] = @index RETURN @rtn END GO
上面代码示例中@index参数即是你想获取第几个字符串,举个例子吧: