多少次我們會面臨這樣的問題:我們需要把一組ID的Array做為參數傳給存儲過程.在存儲過程中能轉換成Table後我們會更喜歡使用這種數據.
這裡我們使用CTE來實現,例如我們有這樣的字符串:'1,2,4,8',想轉成這個table:
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對您有幫助.