T-SQL字符串拆分的多种方式
1、使用拆分SP或者函数。
拆分方法:
Create PROCEDURE [dbo].[ec_System_SplitString]
@strs nvarchar(max),
@separator nchar(1)=','
AS
BEGIN
SET NOCOUNT ON;
DECLARE @tbNames table([Name] nvarchar(256) NOT NULL PRIMARY KEY)
DECLARE @Num int;
DECLARE @Pos int;
DECLARE @NextPos int;
DECLARE @Name nvarchar(256);
SET @Num = 0;
SET @Pos = 1;
WHILE(@Pos <= LEN(@strs))
BEGIN
SELECT @NextPos = CHARINDEX(@separator, @strs, @Pos)
IF (@NextPos = 0 OR @NextPos IS NULL)
SELECT @NextPos = LEN(@strs) + 1
SELECT @Name = RTRIM(LTRIM(SUBSTRING(@strs, @Pos, @NextPos - @Pos)))
SELECT @Pos = @NextPos+1
INSERT INTO @tbNames VALUES (@Name)
SET @Num = @Num + 1
END
SELECT [Name] FROM @tbNames
END
@strs nvarchar(max),
@separator nchar(1)=','
AS
BEGIN
SET NOCOUNT ON;
DECLARE @tbNames table([Name] nvarchar(256) NOT NULL PRIMARY KEY)
DECLARE @Num int;
DECLARE @Pos int;
DECLARE @NextPos int;
DECLARE @Name nvarchar(256);
SET @Num = 0;
SET @Pos = 1;
WHILE(@Pos <= LEN(@strs))
BEGIN
SELECT @NextPos = CHARINDEX(@separator, @strs, @Pos)
IF (@NextPos = 0 OR @NextPos IS NULL)
SELECT @NextPos = LEN(@strs) + 1
SELECT @Name = RTRIM(LTRIM(SUBSTRING(@strs, @Pos, @NextPos - @Pos)))
SELECT @Pos = @NextPos+1
INSERT INTO @tbNames VALUES (@Name)
SET @Num = @Num + 1
END
SELECT [Name] FROM @tbNames
END
通地表变量来使用函数:
declare @tbNames table([Name] nvarchar(256) not null);
insert into @tbNames([Name])
exec ec_System_SplitString @Filter, ',';
select * from @tbNames;
insert into @tbNames([Name])
exec ec_System_SplitString @Filter, ',';
select * from @tbNames;
编写中....