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

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

    You can avoid using dynamic sql by creating a sql function that use a CTE (I found the code below many years ago on sqlservercentral - Amit Gaur) :

    Change the body of your procs with something like this :

    SELECT  p.WPRN AS ID,
    p.Address  AS Address,
    p.Address AS Street
      FROM [dbo].[Properties] AS p
    WHERE 
       p.WPRN NOT IN ( SELECT item FROM dbo.strToTable(@NotNeededWPRNs, ','))
    

    Below the sql code that transforms a string into a table :

    CREATE FUNCTION [dbo].[strToTable] 
    (
        @array varchar(max),
        @del char(1)
    )
    RETURNS 
    @listTable TABLE 
    (
        item int
    )
    AS
    BEGIN
    
        WITH rep (item,list) AS
        (
            SELECT SUBSTRING(@array,1,CHARINDEX(@del,@array,1) - 1) as item,
            SUBSTRING(@array,CHARINDEX(@del,@array,1) + 1, LEN(@array)) + @del list
    
            UNION ALL
    
            SELECT SUBSTRING(list,1,CHARINDEX(@del,list,1) - 1) as item,
            SUBSTRING(list,CHARINDEX(@del,list,1) + 1, LEN(list)) list
            FROM rep
            WHERE LEN(rep.list) > 0
        )
        INSERT INTO @listTable
        SELECT item FROM rep
    
        RETURN 
    END
    

提交回复
热议问题