SQL - 字串分割回傳資料表
DROP FUNCTION [dbo].[fn_slip_str]
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[fn_slip_str]( @InStr nvarchar(max) , @s_char nvarchar(1) )
Returns @tb Table ( sno int , data nvarchar(max) )
As
Begin
/*依據傳入字元進行字串分割,回傳Table*/
/*
Declare @InStr nvarchar(2000) , @s_char nvarchar(1);
Set @InStr = '字串一,字串2,字串3,字串4';
Set @s_char = ',';*/
Set @InStr = @s_char + @InStr + @s_char;
Declare @p1 Int , @p2 Int , @data nvarchar(max) , @sno int;
Set @p1 = -1 ; Set @p2 = -1 ; Set @data = '' ; Set @sno = 0;
While ( 0 Not In (@P1,@P2) ) Begin
Set @p1 = CharIndex(@s_char,@InStr,@p1+1);
Set @p2 = CharIndex(@s_char,@InStr,@p1+1);
If ( 0 In (@p1,@p2) )
Break;
Set @data = SubString(@InStr,@p1+1,@p2-@p1-1);
if ( @data <> '' ) Begin
Set @sno = @sno +1;
Insert Into @tb ( sno , data ) Values ( @sno , @data )
End
End
Return
End
GO