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
Related
Thanks for your time, is there a way to execute the create database part of the statement before the use database name?
I guess I could create 2 set and execute statements but there must be a better way ?
CREATE PROCEDURE [dbo].[Master]
#DBNAME NVARCHAR(50)
AS
DECLARE #CODE NVARCHAR(MAX)
SET #CODE = 'CREATE DATABASE '+#DBNAME+'; USE '+#DBNAME
EXEC SP_Executesql #CODE
Thanks in advance
I am trying to call a scalar function on a linked server but I am having a little trouble setting it up. I am hoping to set it up as a function on my server.
Below is the best I came up with.
I am trying to wrap an openquery statement within the function on my server. However, the query works by itself by I am not able to return the results without causing an error.
USE POWERVIEW
GO
ALTER FUNCTION DBO.FN_VAR_DUMPNAME (#DUMPLOC NVARCHAR(40))
RETURNS NVARCHAR(40)
AS
BEGIN
--DECLARE #DUMPLOC NVARCHAR(40)='D11'
DECLARE #sql nvarchar(800)
DECLARE #param Nvarchar(20)= #DUMPLOC
DECLARE #retval NVARCHAR(40)
DECLARE #ParmDefinition nvarchar(500)=N'#retvalOUT NVARCHAR(40) OUTPUT'
DECLARE #innersql nvarchar(400)
SET #innersql = 'SELECT POWERVIEW.DBO.FN_VAR_DUMPNAME('''+''''+#param +''''+''')'
SET #sql = 'select * from openquery(MINESQLSERVER,'''+ #innersql +''' )'
***RETURN EXEC sp_executesql #sql --This line does not work***
END
This is too long for a comment.
SQL Server does not allow functions to call dynamic SQL. Hence you cannot do what you want.
You have other problems as well:
return exec is not something I've every seen before.
exec returns an integer.
The function returns a string.
You will need to solve your problem using some other method -- a stored procedure comes to mind.
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
This question already has answers here:
SQL: Select dynamic column name based on variable
(3 answers)
Closed 8 years ago.
I have a web page with a link to a stored procedure and I want to pass a variable to the stored procedures select statement. The code so far is -
ALTER procedure [dbo].[RTO]
#Weeknumber int,
#asset nvarchar(50)
AS
Begin
SELECT #asset
FROM RTO_weeklyanalysis
Where weekNumber = #weeknumber
END
basically the #asset will be the name of the column but this will change depending on what the user selects on the page.
You will need to use Dynamic sql for this. Also use QuoteName() function when concatenating object names to your sql query. and use system stored procedure sp_executesql to execute the dynamic query the most safe and secure way of executing dynamic sql. Something as follows :
ALTER procedure [dbo].[RTO]
#Weeknumber int,
#asset sysname
AS
Begin
SET NOCOUNT ON;
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N' SELECT '+ QUOTENAME(#asset) + '
FROM RTO_weeklyanalysis
Where weekNumber = #weeknumber'
EXECUTE sp_executesql #Sql
,N'#Weeknumber int'
,#Weeknumber
END
You cannot use a column name dynamicly in this way. The simplest way to achiewe what you want will be to exec whole query from temporary variable, i mean:
declare #query
set #query = 'SELECT ' + #asset ' FROM RTO_weeklyanalysis Where weekNumber = #weeknumber'
exec sp_executesql #query
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.