Reputation: 33
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.
Upvotes: 1
Views: 6739
Reputation: 33809
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
Upvotes: 2
Reputation: 53
Remove the GO which is between 'AS' and 'SET QUOTED_IDENTIFIER OFF'. The problem is that you declare the variable in a different batch.
Upvotes: 3