循环遍历sql中的动态列表

时间:2013-12-31 15:45:53

标签: sql sql-server list dynamic

我正在编写一个存储过程来读取动态的int值列表(过程的参数)。一旦我读到这个列表,我需要为列表中的每个值插入另一个表。我不是很擅长sql。你能帮我么? 这是我到目前为止所做的。

CREATE PROCEDURE [dbo].[FunctionInsert]
(
    @CONTEXTCODEID INTEGER,
    @MASTERCASEID INTEGER,
    @LETTERCODEIDS VARCHAR(50)
)
IF @LETTERCODEIDS  <> '0'
    BEGIN
    WITH cd AS
    (
        SELECT  1 AS first, CHARINDEX(',', @LETTERCODEIDS  , 1) AS next
        UNION ALL
        SELECT  next + 1, CHARINDEX(',', @LETTERCODEIDS  , next + 1)
        FROM    cd
        WHERE   next > 0
    ),
    lid AS
    (
        SELECT  CAST(SUBSTRING(@LETTERCODEIDS  , first, CASE next WHEN 0 THEN LEN(@LETTERCODEIDS  ) + 1 ELSE next END - first)AS INT) AS id
        FROM    cd
    )
    SELECT * FROM
    (
        SELECT  DISTINCT id
        FROM    lid
    ) l

如果i EXEC FunctionInsert(@LETTERCODEIDS ='1,2,3')

,我将id中的值列表作为1,2,3

现在我需要遍历这些并插入另一个表。

INSERT INTO [dbo].CaseLetters
(
    ContextCodeID,
    MasterCaseID,
    LetterCodeID

)
VALUES
(
    @CONTEXTCODEID,
    @MASTERCASEID ,
    --My values from the list need to go here       
)

我不知道该怎么办。

1 个答案:

答案 0 :(得分:0)

当我发现自己想要在SQL中循环一组值时,我通常最终会使用游标。

假设您的存储过程正在填充名为#tmp_id

的表
DECLARE @ID INT

DECLARE my_cursor CURSOR FOR
SELECT ID FROM #tmp_id

OPEN my_cursor

FETCH NEXT FROM my_cursor INTO @ID

WHILE @@FETCH_STATUS == 0
BEGIN

    -- This is the body of the loop where your logic will go
    -- Every value in the set returned by SELECT ID FROM #tmp_id will
    -- Be bound to the variable @ID for one iteration of this loop

    FETCH NEXT FROM my_cursor INTO @ID
END

CLOSE my_cursor
DEALLOCATE my_cursor

如果我能澄清任何事情,请告诉我。