SQL小程式:對字串進行分割,返回Table(表)物件
經常把儲存過程(含引數)中取得片接的大字串(字串1;字串2;字串3;)進行分割再處理~
比如,其他系統通過WebService介面呼叫,傳入大串工號片接字串(K17000205;K17000658;K16002598;K17001422),程式通過以下邏輯進行分割,返回Table物件.
USE [GSCard01DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <WH>
-- Create date: <2019/01/01>
-- Description: <依據分割符對字串進行分割,返回Table(表)物件>
-- =============================================
ALTER FUNCTION [dbo].[F_Split]
(
@SplitString nvarchar(max), --源字串
@Separator nvarchar(10)=' ' --分隔符號,預設為空格
)
RETURNS @SplitStringsTable TABLE --輸出的資料表
(
[id] int identity(1,1),
[value] nvarchar(max)
)
AS
BEGIN
DECLARE @CurrentIndex int;
DECLARE @NextIndex int;
DECLARE @ReturnText nvarchar(max);
SELECT @CurrentIndex=1;
WHILE(@CurrentIndex<=len(@SplitString))
BEGIN
SELECT @NextIndex=charindex(@Separator,@SplitString,@CurrentIndex);
IF(@NextIndex=0 OR @NextIndex IS NULL)
SELECT @NextIndex=len(@SplitString)+1;
SELECT @ReturnText=substring(@SplitString,@CurrentIndex,@
INSERT INTO @SplitStringsTable([value]) VALUES(@ReturnText);
SELECT @[email protected]+1;
END
RETURN;
END
執行生成小程式,如下:
演示上述小程式的呼叫,程式碼如下:
DECLARE @EmpIDStr nvarchar(max)
set @EmpIDStr ='K17000205;K17000658;K16002598;K17001422'
SELECT * INTO #T1 FROM F_Split(@EmpIDStr, ';')
select * from #T1
--處理結束
DROP TABLE #T1
執行效果,如下