Using variable value in string when executing EXEC in SQL - sql

I want to use a variable value in exec where i don't need to create the query itself.
I will have a query stored in a field in my database and i just want to execute that using the parameters in that stored procedure. For Example below i declared two variables #ValueVariable is the parameter of stored procedure and what i declared #QueryString is the one i will read from data base and i want to execute that using the value of #ValueVariable.
DECLARE #ValueVariable int=0
#QueryString VARCHAR(MAX)=
'SELECT UserName FROM TableUser WHERE UserId=#ValueVariable'
EXEC(#QueryString)
When i try to execute that i get an error Incorrect syntax near 'SELECT UserName FROM TableUser WHERE UserId=#ValueVariable'
I am aware that i can do it by
#QueryString VARCHAR(MAX)=
'SELECT UserName FROM TableUser WHERE UserId='+#ValueVariable
But i want to use it as stated above. Not making a query in my procedure but using variable value as in string retrieved from DB.
So is there any way i could be able to execute that using the value from the variable in current environment.

You can use sp_executesql.
DECLARE
#IntVariable int,
#SQLString nvarchar(500),
#ParmDefinition nvarchar(500)
SELECT
#IntVariable = 0,
#SQLString = N'SELECT UserName FROM TableUser WHERE UserId=#ValueVariable',
#ParmDefinition = N'#ValueVariable INT'
SP_EXECUTESQL
#SQLString,
#ParmDefinition,
#ValueVariable = #IntVariable;
In essence, it creates a one time stored procedure. The #paramDefinition variable is the parameter signature you'd normally see in a stored procedure, the sql server caches the execution plan, etc, etc.

Related

Using Variables Passing Into MSSQL Stored Proc as part of queries

I want to use the value from variables that is passed into the stored proc. Is that allow?
For example, I want to pass CID=5,SID=4 Into an Update Stored Proc
and it looks like this:
CREATE PROCEDURE Update #CID nvarchar(4),#SID nvarchar(4)
AS
DELETE FROM [User"+#CID+#SID+"]
GO;
In which is like "DELETE FROM [User54]"
But I want to dynamically done given the parameter
Can it be done and how is it done?
Thanks
You must use dynamic SQL. To do it safely, ensure the created object name is properly delimited using the quotename function.
Like this:
CREATE OR ALTER PROCEDURE UpdateSomeTable #CID nvarchar(4), #SID nvarchar(4)
AS
begin
declare #tableName nvarchar(500) = quotename(concat('User',#CID,#SID));
declare #sql nvarchar(max) = concat('DELETE FROM ',#tableName);
--print #sql
exec sp_executesql #sql
end

EXEC sp_executesql will work with Integers but not VarChars

I'm using EXEC sp_executesql for a dynamic query in SQL Server 2017.
I've tried various testing scenarios, and I can get results in my query (for other parameters) as long as the values passed in are Integers. So, that means, Location and Department testing works. However, I can't figure out if there's something I need to do differently for when I'm sending a NVARCHAR or DateTime.
Here's my stored procedure, with the NVARCHAR param. Do you see anything I'm doing wrong?
(
#tktitle NVARCHAR(200)
)
AS
BEGIN
Declare #SQL NVARCHAR(MAX)
Set #SQL = 'SELECT timekeep.tkinit, timekeep.tkfirst, timekeep.tklast,
timekeep.tkemdate, timekeep.tktitle, timekeep.tkloc, timekeep.tkdept
FROM abc.xyz'
IF #tktitle IS NOT NULL
Select #SQL = #SQL + 'AND ([tktitle] = #tktitle)'
EXEC sp_executesql #SQL, N'#tktitle varchar', #tktitle
END
I can identify at least three issues:
You need to specify a length for varchar when passing it as a parameter.
You also need a space before the AND and the AND should be a WHERE.
You need to assign the parameter in the execute call.
So:
IF #tktitle IS NOT NULL
Select #SQL = #SQL + ' WHERE ([tktitle] = #tktitle)';
-------------------------^ separator
EXEC sp_executesql #SQL, N'#tktitle varchar(200)', #tktitle=#tktitle;

Scalar variable must be declared in SQL variable

I'm creating a report using sql scripts through management studio and I'm getting the error " Must Declare the scalar variable "#Account". I've been reading other similar questions on this portal but they are related to c#
I'm currently trying to reduce the code on the script so I decided to put a sql script into a variable because depending on a condition the where condition will change. Below is an example of the code
Declare #Account int = 1 , #SQL varchar(max)=''
Select #SQL = N'Select ColumnA,ColumnB, ColumnC from Table1 where ColumnA =1'
if #Account IS NULL
Begin
exec(#SQL)
end
--Here is where the error is hapening
else
begin
--This is the line causing the error
Select #SQL = #SQL + 'AND ColumnB=#Account"
exec(#SQL)
end
If I type manually the value of the variable next to "ColumnB=" it works but the account number will be selected by the user executing the script. I'm thinking on maybe building a temp table to capture the variable value and then do a sub query on the where condition but maybe the solution to this error may be more easier
You want sp_executesql:
select #SQL = #SQL + 'AND ColumnB=#Account';
exec sp_executesql #SQL, N'#Account int', #Account=#Account;
This is how you pass parameters into a dynamic SQL statement in SQL Server. I strongly recommend that you only use sp_executesql to execute SQL statements -- even when you don't have parameters. Using it makes it easy to implement parameters when you need them.
You are passing in '#Account' into the #SQL variable -- the underlying EXEC cannot see that variable.
One way of fixing this would instead be to do this:
Select #SQL = #SQL + 'AND ColumnB=' + CAST(#Account as varchar)

Dynamically get all parameter values in stored procedure

Is there any way to get all parameter values from a stored procedure dynamically?
In other words, iterate through all parameters in one stored procedure to get their values into one string. This is for a unified logging process for a bunch of stored procedures.
I can get the names of parameters:
SELECT PARAMETER_NAME
FROM INFORMATION_SCHEMA.PARAMETER
WHERE SPECIFIC_NAME = 'procedure_name';
Also, I tried to use dynamic SQL commands. I've generated a command with included parameter, but EXEC can't execute command.
#cmd = 'SELECT '#UserID' + CONVERT(NVARCHAR(MAX), #UserID)
+ '#Date' + CONVERT(NVARCHAR(MAX), #Date)'
EXEC #cmd
Is there any way to do this besides manually generating a list of parameter values for each stored procedure?
Since SQL Server 2014 there is sys.dm_exec_input_buffer a table valued function with an output column event_info that gives the full execution statement (including parameters).
I use this for error logging in stored procedures.
For example:
--include this inside the stored procedure
declare #statement nvarchar(max)
select #statement = event_info
from sys.dm_exec_input_buffer(##spid, current_request_id())
--this will print whatever you called the procedure with (including parameters)
print #statement
-- if you want to parse just the parameters from the statement, it can be done like this
declare #proc_name varchar(128) = object_name(##procid)
declare #param_idx int = charindex(#proc_name, #statement) + len(#proc_name)
declare #param_len int = len(#statement) - #param_idx
declare #params nvarchar(max) = right(#statement, #param_len)
select #params

Fully qualified table names with SP_ExecuteSql to access remote server

Trying to update a table on a linked server (SQL 2000/2005) but my server name will not be known ahead of time. I'm trying this:
DECLARE #Sql NVARCHAR(4000)
DECLARE #ParamDef NVARCHAR(4000)
DECLARE #SERVER_NAME VARCHAR(35)
SET #Sql = 'UPDATE
#server_name_param.dba_sandbox.dbo.SomeTable
SET SomeCol=''data'''
SET #ParamDef = N'#server_name_param VARCHAR(35)'
print #Sql
exec sp_executesql #Sql, #ParamDef, #server_name_param=#SERVER_NAME
Which returns this:
UPDATE
#server_name_param.dba_sandbox.dbo.SomeTable
SET SomeCol='data'
Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near '.'.
Any ideas? Is there anyway I view the SQL statement that is being executed after the parameters are bound?
You'll have to do this, it can't be parameterised
....
SET #Sql = 'UPDATE ' + #server_name_param + '.dba_sandbox.dbo.SomeTable SET SomeCol=''data'''
....
Edit: There is another way which I used back in my pure DBA days
EXEC sp_setnetname 'AdhocServer', #SERVER_NAME
UPDATE AdhocServer.dba_sandbox.dbo.SomeTable SET SomeCol 'data'
EXEC sp_setnetname 'AdhocServer', 'MeaninglessValue'
sp_setnetname is there from SQL Server 2000 to 2008
Edit2. Permissions:
Try EXECUTE AS LOGIN = 'login_name' , where login_name is a superuser
I've not really used this (I use "AS USER" for testing), so not sure of the finer points...
Edit 3: for concurrency, consider using sp_getapplock and a stored procedure, or some other concurrency control mechanism.
You cannot do this with parameters directly - you would have to use dynamic SQL, or send the server name as a parameter to an SP that does dynamic SQL:
DECLARE #template NVARCHAR(4000)
DECLARE #Sql NVARCHAR(4000)
DECLARE #SERVER_NAME VARCHAR(35)
SET #template = 'UPDATE {#server_name_param}.dba_sandbox.dbo.SomeTable SET SomeCol=''data'''
SET #sql = REPLACE(#template, '{#server_name_param}', #SERVER_NAME)
print #Sql
exec sp_executesql #Sql -- OR EXEC ( #sql )
I like gbn's trick. I didn't know that one and I'm gonna have to research that some more.
Since I didn't know that trick, I've had to use dynamic sql in similar situations in the past (like what Cade posted). When that happens I would normally query an information schema view to make sure the parameter value is a real database object before building the query. That way I'm sure it's not an injection attempt.