I've been wondering if it's possible to declare and set a variable within the definition of another variable.
For example:
declare #variable varchar(250)
set #variable =
'INSERT INTO [BLAH] (Nope, Hype, Friends)
VALUES (declare #value varchar(250) set #value = 'example' exec #value, #value, #value)'
exec #variable
I'm probably doing multiple really basic mistakes here - just trying to understand as much as fast as possible
it can be done as below.
declare #variable varchar(800)
set #variable =
' declare #value varchar(10) = ''example''
INSERT INTO [BLAH] (Nope, Hype, Friends)
VALUES ( #value, #value, #value)'
exec #variable
Also get a knowledge of SQL injection before you work with dynamic sql.
Yes you can declare a set of variable inside a variable: doing like this.
DECLARE #variable varchar(max)
SET #variable =
'declare #value varchar(max) = ''example''
Insert into BLAH
values(#value,#value)'
EXEC (#variable)
Here we simply declared a variable #value inside another variable #variable
Related
I have a SQL query stored in a table that contains parameter names. I need to know how to execute it properly in a stored procedure.
This is my SQL code in the procedure
PROCEDURE [spMassUpdateSKUs]
#SKU AS NVARCHAR(20)
,#FIELD AS NVARCHAR(50)
,#VALUE AS NVARCHAR(50)
,#RESULT as Int = Null Output
AS
BEGIN
IF EXISTS(SELECT CODENUMBER FROM INVENTORY_MASTER WHERE CODENUMBER=#SKU)
BEGIN
DECLARE #SQLQUERY AS NVARCHAR(50)
SET #SQLQUERY=(SELECT SQLUPDATE FROM MASS_UPDATE WHERE DROPDOWNLABEL=#FIELD)
EXEC SP_EXECUTESQL #SQLQUERY
END
and this is the sql query from the table
update inventory_master_flex set departmentid=#value where codenumber=#sku
I've tried replacing with the real parameters but that doen't work.
SELECT REPLACE(REPLACE(#SQLQUERY,'#VALUE',#VALUE),'#SKU',#SKU)
-- 50 is too short for sure; you may try 1000 or different number
DECLARE #SQLQUERY AS NVARCHAR(MAX)
-- for debug purpose
PRINT #SQLQUERY
-- params
EXEC SP_EXECUTESQL #SQLQUERY, N'#Value NVARCHAR(50), #sku NVARCHAR(50)`, #Value, #sku
REPLACE is not good in case of strings with quotes and so on which would brake the #sqlquery code.
Pass the parameters in using sp_executesql, not replace():
IF EXISTS(SELECT CODENUMBER FROM INVENTORY_MASTER WHERE CODENUMBER=#SKU)
BEGIN
DECLARE #SQLQUERY AS NVARCHAR(MAX);
SET #SQLQUERY = (SELECT SQLUPDATE FROM MASS_UPDATE WHERE DROPDOWNLABEL = #FIELD);
EXEC SP_EXECUTESQL #SQLQUERY, N'#SKU VARCHAR(255), #VALUE VARCHAR(255)', #SKU = #SKU, #VALUE = #VALUE
END;
I don't know what the types are. But if one or both are strings or dates, then you would need single quotes in your implementation. However, you are already using sp_executesql so go whole-hog and pass in parameters as well.
I'm building a dynamic query. Inside it, I have declare variables. Now I want to concatenate this variable in my insert query
declare #qry nvarchar(MAX)
select #qry='Declare #var1 nvarchar(10); set #var1 =''abcd''
insert into mytable (col1) values ('+#var1+')'
When I execute this code it give me an error
Must declare the scalar variable "#var1".
But if I declare #var1 outside #qry then it works fine.I am having problem in concatenating the value of variable.
Please help
Thanks
You cannot do that. The context of execution of Dynamic query is different from the outer script.
this will work
declare #qry nvarchar(MAX)
Declare #var1 nvarchar(10);
set #var1 ='abcd'
select #qry='insert into mytable (col1) values ('+#var1+')'
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
Is there a way to get a value of a local variable specified by its name dynamically in SQL Server SP?
declare #foo int
declare #bar int
declare #variable_name varchar(10)
set #variable_name = '#foo'
print -- magic happens here - how to print the value of the variable
-- which name is stored in #variable_name, in this case #foo
eval won't help since it does not have access to local variables of the enclosing scope.
I'm doing this for debugging/diagnostics purposes mostly.
Technically this is possible by passing all local variables to sp_executesql:
declare #foo int
declare #bar int
declare #variable_name varchar(10)
set #variable_name = '#foo'
set #foo = 1;
set #bar = 2;
declare #sql nvarchar(max);
set #sql = N'SELECT ' + #variable_name;
exec sp_executesql #sql, N'#foo int, #bar int', #foo, #bar
Of course this would be quite hard to maintain in real life, the call to sp_executesql would have to be constantly kept up to date with the local variables on the current frame (batch or procedure call). While this is somewhat 'generic', is hardly any better than using a big CASE with all local variable names.
AFAIK, no: there is no direct way of doing this on SQL Server.
declare #foo int
declare #bar int
select #foo=1, #bar=2
declare #variable_name varchar(10)
set #variable_name = '#foo'
if #variable_name = '#foo'
print #foo
else if #variable_name = '#bar'
print #bar
I have the below SQL..What I am trying to do is use the Parameter defined at the stored procedure level inside dynamic SQL:
CREATE PROCEDURE [dbo].[Test]
(#DealID NVARCHAR(500),
#OUTPUT NVARCHAR(MAX) OUTPUT,
#FeeType CHAR(1)
) -- I want to use this parameter inside dynamic SQL query
AS
DECLARE #exec_str NVARCHAR(MAX)
DECLARE #ParmDefinition NVARCHAR(MAX)
BEGIN
SET #exec_str = N'DECLARE #ParmDefinition NVARCHAR(500)
SELECT * FROM #FeeType' --This is where I want to use the variable
DECLARE #ParamDefinition nvarchar(max)
SET #ParamDefinition = N'#OUTPUT NVARCHAR(MAX) OUTPUT'
EXEC sp_executesql #exec_str, #ParamDefinition
Can someone please tell me how to do it?
Thanks
In SQL Server Identifiers can't be parameterized.
Since you are using dynamic SQL anyway, you can do something like this:
SET #exec_str= N'Select * from '+ #FeeType
EXEC(#exec_str)
However, this is vulnerable to SQL injection attacks. To reduce the risk to minimum you should check first that such a table name exists, and I would also use quotename just to be on the safe side:
IF EXISTS
(
SELECT 1
FROM Information_Schema.Tables
WHERE TABLE_NAME = #FeeType
)
BEGIN
SET #exec_str= N'Select * from '+ QUOTENAME(#FeeType)
EXEC(#exec_str)
END