简体   繁体   中英

Must declare the scalar variable error SQL

I have this SQL statement, but i have error Must declare the scalar variable "@InputPath"

IF OBJECT_ID('DBO.SP_INSERT_REQUESTS') IS NULL BEGIN
    EXEC('CREATE PROCEDURE DBO.SP_INSERT_REQUESTS AS RETURN')
    GRANT EXECUTE ON DBO.SP_INSERT_REQUESTS TO PUBLIC
END
GO
ALTER PROCEDURE DBO.SP_INSERT_REQUESTS    
    @Name NVARCHAR(512), 
    @Code NVARCHAR(50),
    @InputPath NVARCHAR(2000),
    @OutputPath NVARCHAR(2000)
AS
GO

SET QUOTED_IDENTIFIER OFF

--DECLARE @InputPath varchar(2000) = "c:\MyDoc1.xsd"

DECLARE @InputValue XML

--DECLARE @OutputPath varchar(2000) = "c:\MyDoc2.xsd"

DECLARE @OutputValue XML

DECLARE @QUERY NVARCHAR(4000) SET @QUERY  = "
    SELECT @InputValue = InputExample.BulkColumn
    FROM OPENROWSET (BULK '"+@InputPath+"', SINGLE_BLOB) AS InputExample;   

    SELECT @OutputValue = InputExample.BulkColumn
    FROM OPENROWSET (BULK '"+@OutputPath+"', SINGLE_BLOB) AS InputExample;
"   

EXEC SP_EXECUTESQL @QUERY, N'@InputValue XML out, @OutputValue XML out', @InputValue out, @OutputValue out

INSERT INTO MyTable(Name, Code, Input, Output)
VALUES('value1', 'value2' , @InputValue, @OutputValue)

I have declared the parameters, so I don't understand why I am getting the error.

Remove the GO which is between 'AS' and 'SET QUOTED_IDENTIFIER OFF'. The problem is that you declare the variable in a different batch.

Dynamic sql runs in a different session and therefore variables defined outside the dynamic query will not be available to the dynamic query DEMO - HERE .

Then again, if you declare them within the dynamic query, they won't be available outside the query. DEMO - HERE

I can see why you using dynamic sql as you cannot pass parameter to openrowset. I think you could do something like this to over come the issue. DEMO

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