如何在SQL Server中循环遍历表类型的变量?

时间:2017-11-08 15:14:06

标签: sql sql-server database

这是我第一个问题的连续性,我想在SQL Server变量中存储多个值。我需要遍历@tranId变量,该变量包含两个值,然后根据我在@tranId中的ID删除一个事务。

这就是我的查询的样子。

ALTER PROCEDURE "ESG"."SP_ADD_TEST_DATA"
AS
BEGIN

DECLARE @envelopeId table(identifiers VARCHAR(1000));

INSERT INTO @envelopeId (identifiers) VALUES('axaa1aaa-aaaa-a5aa-aaaa-aa8aaaa9aaaa');
INSERT INTO @envelopeId (identifiers) VALUES('bxbb1bbb-bbbb-b5bb-bbb4-bb8bbbb9bbbf');

DECLARE @tranId table(ids INT);
INSERT INTO @tranId SELECT DOCUMENT_SET_TRANSACTION_ID FROM ESG.DOCUMENT_SET_TRANSACTION WHERE IDENTIFIER IN (SELECT identifiers FROM @envelopeId); 

BEGIN
    DECLARE @transactionId int;
    DECLARE @tranId_cursor CURSOR;
    SET @tranId_cursor = CURSOR FOR 
    SELECT * FROM @tranId;

    OPEN @tranId_cursor
    FETCH NEXT FROM @tranId_cursor INTO @transactionId;

    WHILE @@FETCH_STATUS = 0
    BEGIN
            DELETE FROM ESG.DOCUMENT_SET_TRANS_MDATA WHERE DOCUMENT_SET_TRANSACTION_ID = @transactionId;
    END
END
CLOSE @tranId_cursor;
DEALLOCATE @tranId_cursor;
END

这变得越来越复杂,我不确定如何优雅地实现这一目标。

由于

2 个答案:

答案 0 :(得分:0)

如果我明白你在问什么,这就是我认为你应该做的事情

由于@tranId是一个表,您可以将游标创建为

DECLARE tran_cursor CURSOR  
FOR SELECT * FROM @tranId;

并在WHILE循环中,使用

获取其内容

OPEN tran_cursor FETCH NEXT FROM tran_cursor INTO @rec;

您可以在要使用的删除内的@ rec.ids中访问这些值。

您可以在https://docs.microsoft.com/en-us/sql/t-sql/language-elements/while-transact-sql中找到更多信息 以及https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql

答案 1 :(得分:0)

您可以使用直接使用第一个表变量的DELETE语句,如下所示:

DELETE ESG.DOCUMENT_SET_TRANS_MDATA
WHERE DOCUMENT_SET_TRANSACTION_ID IN
   (SELECT DOCUMENT_SET_TRANSACTION_ID
    FROM ESG.DOCUMENT_SET_TRANSACTION
    WHERE IDENTIFIER IN
       (SELECT identifiers FROM @envelopeId)
   )

作为替代方案,也可以在不使用任何表变量的情况下完成:

DELETE ESG.DOCUMENT_SET_TRANS_MDATA
WHERE DOCUMENT_SET_TRANSACTION_ID IN
   (SELECT DOCUMENT_SET_TRANSACTION_ID
    FROM ESG.DOCUMENT_SET_TRANSACTION
    WHERE IDENTIFIER IN
       ('axaa1aaa-aaaa-a5aa-aaaa-aa8aaaa9aaaa',
        'bxbb1bbb-bbbb-b5bb-bbb4-bb8bbbb9bbbf'
       )
   )