Using a table variable inside of a exists statement

后端 未结 3 1028
隐瞒了意图╮
隐瞒了意图╮ 2021-02-20 09:47

I am trying to update a column inside of a table variable based on a condition, the condition being that the ID of the table variable does not exist in a different table:

<
相关标签:
3条回答
  • 2021-02-20 10:14

    This is actually very picky. Check out the in-line comments below using womp's suggestion and also trying a LEFT OUTER JOIN.

    CREATE TABLE Bug (CODE VARCHAR(50))
    
    DECLARE @BugRep TABLE (
        BugCode         VARCHAR(50),
        --DevFirstName    VARCHAR(50),
        --DevLastName     VARCHAR(50),
        --BugDate         VARCHAR(20),
        IsValid         CHAR(1)
    )
    
    INSERT INTO Bug (CODE) VALUES ('Code1'), ('Code2'), ('Code3')
    
    INSERT INTO @BugRep (BugCode) VALUES ('Code1'), ('Code2'), ('Code4')
    
    SELECT CODE FROM Bug ORDER BY CODE
    SELECT BugCode, IsValid FROM @BugRep ORDER BY BugCode
    
    UPDATE @BugRep                          -- Can't be [@BugRep] ("Invalid object name '@BugRep'.")
    SET IsValid = 'N'
    WHERE NOT EXISTS (
        SELECT *
        FROM BUG b
        WHERE [@BugRep].BUGCODE = b.CODE    -- Can't be @BugRep ("Must declare the scalar variable "@BugRep".")
    )
    
    SELECT BugCode, IsValid FROM @BugRep ORDER BY BugCode
    
    UPDATE @BugRep                          -- Can be either @BugRep or [@BugRep]
    SET IsValid = 'Y'
    FROM @BugRep                            -- Can't be [@BugRep] ("Invalid object name '@BugRep'.")
    LEFT OUTER JOIN BUG
    ON [@BugRep].BUGCODE = BUG.CODE         -- Can't be @BugRep ("Must declare the scalar variable "@BugRep".")
    WHERE BUG.CODE IS NOT NULL
    
    SELECT BugCode, IsValid FROM @BugRep ORDER BY BugCode
    
    DROP TABLE Bug
    GO
    
    0 讨论(0)
  • 2021-02-20 10:20

    This will work:

    [@BugRep].BUGCODE
    

    You'll also need to change "b.CODE" to "b.BUGCODE" by the way ;)

    0 讨论(0)
  • 2021-02-20 10:36

    Here's a version of the previous two using aliases to get around your issue:

    UPDATE @BugRep
    SET IsValid = 'N'
    FROM @BugRep BR
        LEFT JOIN BUG B
            ON BR.BUGCode = B.CODE
    WHERE B.CODE is null
    

    This also avoids the inefficiencies related to "is not null" and "not exists".

    0 讨论(0)
提交回复
热议问题