一、创建测试表
Employees
二、创建表值函数
-- DROP FUNCTION TableIntSplit;
CREATE FUNCTION TableIntSplit(@Text NVARCHAR(4000),@Sign NVARCHAR(4000))
RETURNS @tempTable TABLE(Id INT )
AS
BEGIN
DECLARE @StartIndex INT
DECLARE @FindIndex INT
DECLARE @Content VARCHAR(4000)
SET @StartIndex = 1
SET @FindIndex=0
WHILE(@StartIndex <= LEN(@Text))
BEGIN
SELECT @FindIndex = CHARINDEX(@Sign,@Text,@StartIndex)
IF(@FindIndex =0 OR @FindIndex IS NULL)
BEGIN
SET @FindIndex = LEN(@Text)+1
END
SET @Content = LTRIM(RTRIM(SUBSTRING(@Text,@StartIndex,@FindIndex-@StartIndex)))
SET @StartIndex = @FindIndex+1
INSERT INTO @tempTable ([Id]) VALUES (convert(int, @Content))
END
RETURN
END;
测试
select * from Employees(NOLOCK)
select * from dbo.TableIntSplit('1,2,3,4,5,6',',')
select t1.LastName,t2.Id from Employees(NOLOCK) t1 join dbo.TableIntSplit('1,2,3,4,5,6',',') t2 on t1.EmployeeID=t2.Id