MS SQL Server沒有split()函數,但是我們可以寫一個Table-valued Functions定義函數[dbo].[udf_SplitStringToTable] : CREATE FUNCTION [dbo].[udf_SplitStringToTable] ( @string ...
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 ENDSource Code
再寫另外一個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 GOSource Code
上面代碼示例中@index參數即是你想獲取第幾個字元串,舉個例子吧: