简体   繁体   中英

Error while executing BCP Script - Must declare the scalar variable @v

Description: I have created a stored procedure which will create a pipe separated flat file for the range between from & to id's which are passed as parameters ie @from & @to.

The third parameter ie @v is a temp variable which will get the incremented value in the loop & this will be used in the where condition of the query.

When I execute the stored procedure in SQL Server, I get an error

Must declare the scalar variable @v

This is my stored procedure:

ALTER PROCEDURE [dbo].[FlatFileCreate]
    @from INT, 
    @to INT,
    @v INT
AS
BEGIN
    WHILE(@from <= @to)
    BEGIN
        SET @v = @from;

        DECLARE @cmd varchar(2000)

        SET @cmd = 'bcp "SELECT * FROM SDB.dbo.Customer WHERE ID=@v  " queryout "c:\output_Aug27.txt" -c -T -t "|" -SOLA-DB'

        EXEC master..xp_cmdshell @cmd

        SET @from = @from + 1;  
    END
    RETURN 0
END

Thanks in advance

Within your dynamic command there's no @v

ALTER PROCEDURE [dbo].[FlatFileCreate]
    @from INT, 
    @to INT,
    @v INT
AS
BEGIN
    WHILE(@from <= @to)
    BEGIN
        SET @v = @from;

        DECLARE @cmd varchar(2000)

        SET @cmd = 'bcp "SELECT * FROM SDB.dbo.Customer WHERE ID=' + CAST(@v AS VARCHAR(MAX)) + '  " queryout "c:\output_Aug' + CAST(@v AS VARCHAR(MAX)) + '.txt" -c -T -t "|" -SOLA-DB'

        EXEC master..xp_cmdshell @cmd

        SET @from = @from + 1;  
    END
    RETURN 0
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM