SQLSERVER2008使用CTE转换string到Table

多少次我们会面临这样的问题:我们需要把一组ID的Array做为参数传给存储过程.在存储过程中能转换成Table后我们会更喜欢使用这种数据.

这里我们使用CTE来实现,例如我们有这样的字符串:'1,2,4,8',想转成这个table:

4295 

T-sql:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:         Amit Gaur
-- Create date: July 25th 2008
-- Description:    Convert a string to a table
-- =============================================
CREATE FUNCTION [dbo].[strToTable] 
(
    @array varchar(max),
    @del char(1)
)
RETURNS 
@listTable TABLE 
(
    item int
)
AS
BEGIN
    
    WITH rep (item,list) AS
    (
        SELECT SUBSTRING(@array,1,CHARINDEX(@del,@array,1) - 1) as item,
        SUBSTRING(@array,CHARINDEX(@del,@array,1) + 1, LEN(@array)) + @del list
 
        UNION ALL
 
        SELECT SUBSTRING(list,1,CHARINDEX(@del,list,1) - 1) as item,
        SUBSTRING(list,CHARINDEX(@del,list,1) + 1, LEN(list)) list
        FROM rep
        WHERE LEN(rep.list) > 0
    )
    INSERT INTO @listTable
    SELECT item FROM rep
 
    RETURN 
END
 
GO

如何调用呢:

   1:  DECLARE @array VARCHAR(max)
   2:  SET  @array = '1,2,4,8'
   3:  SELECT item FROM strToTable(@array,',')


完了,实际以前你可以用function递归来实现,这里我们使用CTE.希望这篇POST对您有帮助.

Post of Author: Petter Liu    http://wintersun.cnblogs.com

你可能感兴趣的:(sqlserver)