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

前端 未结 4 2102
忘了有多久
忘了有多久 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:11

    The reason you get this error is that the scope of table variables is limited to a single batch, since sp_executesql runs in its own batch, it has no knowledge that you have declared it in another batch.

    It works when you @NotNeededWPRNs is NULL because concatenating NULL yields NULL (unless otherwise set), so you are just executing:

    exec sp_executesql null;
    

    I would also say, if you are using SQL Server 2008 or later please consider using table valued parameters instead of a delimited list of strings. This is much safer and more efficient, and validates the input, if I were to pass 1); DROP TABLE dbo.Prioperties; -- as @NotNeededWPRNs, you could find yourself without a properties table.

    First you would need to create the type (I tend to use a generic name for reusability):

    CREATE TYPE dbo.IntegerList TABLE (Value INT);
    

    Then you can add it to your procedure:

    CREATE PROCEDURE [dbo].[GetNeededProperties]
        @NotNeededWPRNs dbo.IntegerList READONLY,
        @LastSynch DATETIME,
        @TechCode VARCHAR(5)
        AS
        BEGIN
    
        SELECT  p.WPRN AS ID,
                p.Address  AS Address,
                p.Address AS Street
         FROM   [dbo].[Properties] AS p
        WHERE   p.WPRN NOT IN (SELECT Value FROM @NotNeededWPRNs)
    

    On an unrelated note, you should avoid using culture sensitive date formats where possible, 06/28/2013 is clearly supposed to be 28th June in this case, but what about 06/07/2013, without setting DATEFORMAT, or the language how do you know if this will be read as 6th July or 7th June? The best format to use is yyyyMMdd, it is never ambiguous, even the ISO standard format yyyy-MM-dd can be interpreted as yyyy-dd-MM in some settings.

提交回复
热议问题