在T-SQL中咱們常常批量操做時都會對字符串進行拆分,但是SQL Server中卻沒有自帶Split函數,因此要本身來實現了。這裏將字符串分割以table形式輸出
語法以下:c#
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /* create by shuke.li 2020-9-15 */ create function [dbo].[SplitString] ( @Input nvarchar(max), --input string to be separated @Separator nvarchar(max)=',', --a string that delimit the substrings in the input string @RemoveEmptyEntries bit=1 --the return value does not include array elements that contain an empty string ) returns @TABLE table ( [Id] int identity(1,1), [Value] nvarchar(max) ) as begin declare @Index int, @Entry nvarchar(max) set @Index = charindex(@Separator,@Input) while (@Index>0) begin set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1))) if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') begin insert into @TABLE([Value]) Values(@Entry) end set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input)) set @Index = charindex(@Separator, @Input) end set @Entry=ltrim(rtrim(@Input)) if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') begin insert into @TABLE([Value]) Values(@Entry) end return end
只要在新建查詢裏執行上面的代碼,即完成了split函數的創建。
下面來測試這一函數的功能,測試所使用的的SQL腳本以下:ide
declare @str1 varchar(max) set @str1 = 'CFER-3345-3323,CFER-0023-2299,CFER-0023-6677,CFER-0023-7678,CFER-4565-2299,CFER-0023-6678' select * from [dbo].[SplitString](@str1, ',', 0)
結果顯示以下圖所示:函數
最終使用方法和c#中的split函數是否是很類似!測試