“Must declare the table variable ”@name“” in stored procedure

前端 未结 4 2104
忘了有多久
忘了有多久 2021-02-19 05:56

I have a procedure which returns the error:

Must declare the table variable \"@PropIDs\".

But it is followed with the message:

4条回答
  •  死守一世寂寞
    2021-02-19 06:14

    The issue is that you're mixing up dynamic SQL with non-dynamic SQL.

    Firstly - the reason it works when you put NULL into @NotNeededWPRNs is because when that variable is NULL, your @ProductsSQL becomes NULL.

    WHat you need to do is either make your @PropsIDs table a non-table variable and either a temporary table or a physical table. OR you need to wrap everything in dynamic SQL and execute it.

    So the easy way is to do something like this:

    Declare @ProductsSQL nvarchar(max);
        SET @ProductsSQL = '
        DECLARE @PropIDs TABLE
        (ID bigint)
        Insert into @PropIDs (ID) 
        SELECT [WPRN] FROM [dbo].[Properties] WHERE(WPRN in (' + @NotNeededWPRNs + '))
    
        SELECT  p.WPRN AS ID,
        p.Address  AS Address,
        p.Address AS Street
          FROM [dbo].[Properties] AS p
        WHERE 
           p.WPRN NOT IN( SELECT ID FROM @PropIDs)
        '
    

    and execute that. OR as mentioned - change @ProdIDs to a temporary table. (The route you're approaching in the CREATE #ProdIds, but then you need to use #ProdIDs instead of @ProdIDs everywhere in the sproc).

提交回复
热议问题