Error with declaring scalar variable in dynamic SQL - sql-server

I am working in SQL Server 2008. I have the following stored procedure that has a dynamic SQL statement in it:
CREATE PROCEDURE dbo.test
#list_of_codes varchar(255) = NULL,
#test_ID int = NULL
AS
DECLARE #sql1 nvarchar(max)
SELECT #sql1 =
'
INSERT INTO some_table
SELECT
some_col AS Some_Column,
#test_ID AS Testing_Identifier
FROM some_table
WHERE
testing_number_col = #test_ID
AND
test_col NOT IN (''' + REPLACE( #list_of_codes, ',', ''',''') + ''')
'
EXEC sp_executesql #sql1
'
I execute this stored procedure with the following statement:
EXEC dbo.test #list_of_codes = 'x,y,z', #test_ID = 10
When I execute this statement, an error is thrown, stating
Must declare the scalar variable ''test_ID''.
I'm sure my error is something as simple as escaping the #test_ID scalar variable in the dynamic SQL statement, but I don't see where I need to escape it (if that is really my problem). What am I doing wrong?

You are missing quotes
Considering that #test_ID is of Integer Type. If #test_ID is of varchar type then you may have to add additional quotes
SELECT #sql1 =
'
INSERT INTO some_table
SELECT
some_col AS Some_Column,
'+convert(varchar(20),#test_ID)+' AS Testing_Identifier
FROM some_table
WHERE
testing_number_col = '+ convert(varchar(20),#test_ID) + '
AND
test_col NOT IN (''' + REPLACE( #list_of_codes, ',', ''',''') + ''')
'

The dynamic part of your query knows nothing of the parameters in the outer stored procedure, so you must declare them when calling sp_executesql
This is covered in the documentation.
In your example you could use
DECLARE #sql1 nvarchar(max)
DECLARE #Params NVARCHAR(MAX) = '#test_ID INT'
SELECT #sql1 =
'
INSERT INTO some_table
SELECT
some_col AS Some_Column,
#test_ID AS Testing_Identifier
FROM some_table
WHERE
testing_number_col = #test_ID
AND
test_col NOT IN (''' + REPLACE( #list_of_codes, ',', ''',''') + ''')'
EXEC sp_executesql #sql1, #Params, #Test_ID=#Test_ID

Related

SQL Server Table Parameter without defining fields [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

How to make a query with dynamic column in sql server 2012

I have the sample code below. The result is such that it takes as these columns as VARCHAR type.
declare #col1 varchar(80)='[Column1]'
declare #col2 varchar(80)='[Column2]'
SELECT #col1,#col2 FROM MyTable
You have to use dynamic SQL:
DECLARE #col1 VARCHAR(80) = 'Column1';
DECLARE #col2 VARCHAR(80) = 'Column2';
DECLARE #sql NVARCHAR(MAX);
SELECT #sql = 'SELECT ' + QUOTENAME(#col1) + ', ' + QUOTENAME(#col2) + ' FROM MyTable;';
EXEC sp_executesql #sql;
Note that you have to make sure that your column names are real column names. You also need to parameterize your query for added security. If you get any of these wrong, it may create huge security problems.
Try,
declare #query nvarchar(500) = 'select ' + #col1 + ', ' + #col1 + ' FROM MyTable'
exec #query

Column name not working when placed inside a variable in SQL Server [duplicate]

create procedure sp_First
#columnname varchar
AS
begin
select #columnname from Table_1
end
exec sp_First 'sname'
My requirement is to pass column names as input parameters.
I tried like that but it gave wrong output.
So Help me
You can do this in a couple of ways.
One, is to build up the query yourself and execute it.
SET #sql = 'SELECT ' + #columnName + ' FROM yourTable'
sp_executesql #sql
If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.
Alternatively, you can write a CASE statement...
SELECT
CASE #columnName
WHEN 'Col1' THEN Col1
WHEN 'Col2' THEN Col2
ELSE NULL
END as selectedColumn
FROM
yourTable
This is a bit more long winded, but a whole lot more secure.
No. That would just select the parameter value. You would need to use dynamic sql.
In your procedure you would have the following:
DECLARE #sql nvarchar(max) = 'SELECT ' + #columnname + ' FROM Table_1';
exec sp_executesql #sql, N''
Try using dynamic SQL:
create procedure sp_First #columnname varchar
AS
begin
declare #sql nvarchar(4000);
set #sql='select ['+#columnname+'] from Table_1';
exec sp_executesql #sql
end
go
exec sp_First 'sname'
go
This is not possible. Either use dynamic SQL (dangerous) or a gigantic case expression (slow).
Create PROCEDURE USP_S_NameAvilability
(#Value VARCHAR(50)=null,
#TableName VARCHAR(50)=null,
#ColumnName VARCHAR(50)=null)
AS
BEGIN
DECLARE #cmd AS NVARCHAR(max)
SET #Value = ''''+#Value+ ''''
SET #cmd = N'SELECT * FROM ' + #TableName + ' WHERE ' + #ColumnName + ' = ' + #Value
EXEC(#cmd)
END
As i have tried one the answer, it is getting executed successfully but while running its not giving correct output, the above works well
You can pass the column name but you cannot use it in a sql statemnt like
Select #Columnname From Table
One could build a dynamic sql string and execute it like EXEC (#SQL)
For more information see this answer on dynamic sql.
Dynamic SQL Pros and Cons
As mentioned by MatBailie
This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names
CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
(
#fromColumnName varchar(10) ,
#toColumnName varchar(10) ,
#ID varchar(10)
)
as
begin
-- this is the column required for where clause
declare #colname varchar(50)
set #colname=case #fromUserType
when 'XX' then 'XX'
when 'YY' then 'YY'
end
select SelectedColumnId from (
select
case #toColumnName
when 'XX' then tablename.XX
when 'YY' then tablename.YY
end as SelectedColumnId,
From tablename
where
(case #fromUserType
when 'XX' then XX
when 'YY' then YY
end)= ISNULL(#ID , #colname)
) as tbl1 group by SelectedColumnId
end
First Run;
CREATE PROCEDURE sp_First #columnname NVARCHAR(128)--128 = SQL Server Maximum Column Name Length
AS
BEGIN
DECLARE #query NVARCHAR(MAX)
SET #query = 'SELECT ' + #columnname + ' FROM Table_1'
EXEC(#query)
END
Second Run;
EXEC sp_First 'COLUMN_Name'
Please Try with this.
I hope it will work for you.
Create Procedure Test
(
#Table VARCHAR(500),
#Column VARCHAR(100),
#Value VARCHAR(300)
)
AS
BEGIN
DECLARE #sql nvarchar(1000)
SET #sql = 'SELECT * FROM ' + #Table + ' WHERE ' + #Column + ' = ' + #Value
--SELECT #sql
exec (#sql)
END
-----execution----
/** Exec Test Products,IsDeposit,1 **/

SQL Server insert parameterized name table to IF EXISTS

I want to insert #inputData to ColumnData if it doesn't exists to prevent duplicate data to a table with name as parameter #TableName. Error at the 'dbo.#TableName'.
SET #insertSQL = 'INSERT INTO '+ #TableName + ' (ColumnData) VALUES ('''+#inputData+''');'
IF NOT EXISTS (SELECT 1 FROM [dbo].[#TableName] WHERE ColumnData = #inputData)
EXECUTE(#insertData) -- EXECUTE #insertData if ColumnData is not found
I also tried this (also throws error):
SET #insertSQL = 'INSERT INTO '+ #TableName + ' (ColumnData) VALUES ('''+#inputData+''');'
IF NOT EXISTS (EXECUTE('SELECT 1 FROM [dbo]. '+#TableName ' WHERE ColumnData = ' + #inputData))
EXECUTE(#insertData) -- EXECUTE #insertData if ColumnData is not found
It look like you are splitting the dynamic SQL statement. Try something like this:
DECLARE #SQL NVARCHAR(MAX) = N'
IF NOT EXISTS (SELECT 1 FROM dbo.' + QUOTENAME(#TableName) + ' WHERE ColumnData = #inputData
INSERT INTO ' + QUOTENAME(#TableName) + ' (ColumnData) VALUES (#inputData)'
EXEC sp_executesql #SQL, N'#inputData VARCHAR(128)', #inputData = #inputData
Table name cannot be parameterized, so it must be appended. However, QUOTENAME is strongly recommended to avoid SQL injection.
On the other hand, #inputData can be sent as a parameter, that's why sp_executesql can be used.
Generally speaking, unless you are not dealing with parameters, try to always use sp_executesql instead of simple EXEC (), as EXEC forces into ugly string concatenation and possible injectable SQL statements.

SQL Server EXEC backup table with date dynamically

I am looking to backup a table and auto add the date to the end of the table name.
Here is what I have
declare #table char(36)= 'template_fields'
EXEC('select * into '+#table+'_'+'convert(date, getdate()) from '+#table)
And I want the end result to look something like
template_fields_09-09-2015
What am I missing here?
Just print what you do:
DECLARE #table NVARCHAR(MAX) = 'tab';
DECLARE #sql NVARCHAR(MAX) = 'select * into '+#table+'_'
+'convert(date, getdate()) from '+#table;
SELECT #sql;
you will get: select * into tab_convert(date, getdate()) from tab
You need to pass date with table name like:
SqlFiddleDemo
DECLARE #table NVARCHAR(MAX) = 'tab';
DECLARE #new_table NVARCHAR(MAX) = #table + '_' +
CONVERT(NVARCHAR(100), GETDATE(),105);
DECLARE #sql NVARCHAR(MAX) = 'select * into ' + #new_table + ' from '+ #table;
SELECT #sql;
/* Result select * into tab_09-09-2015 from tab */
-- EXEC(#sql);
First of all, do not use EXEC to run dynamic queries, use sp_executesql instead.
Second: When you want to build a SQL query with variable object names, use QUOTENAME().
DECLARE #table sys.sysname = 'mytable'
DECLARE #backup sys.sysname = #table + '_' + CONVERT(date, GETDATE());
DECLARE #sql NVARCHAR(MAX) = 'SELECT * INTO '
+ QUOTENAME(#backup) + ' '
+ FROM + ' '
+ QUOTENAME(#table);
EXEC sp_executesql
#stmt = #sql
Please note that, the sys.sysname is a built in data type (essentially an alias for NVARCHAR(128) NOT NULL) and SQL Server uses it internally for object names.
Note: I have no SQL Server instance accessible right now, so the above query can contain typos.
I ended up resolving this myself. While some nice responses were added I wrote my initial query more simply to achieve this. Thank you all for the help.
--Declare and initiate the table
declare #table varchar(36)= 'template_fields'
--Declare and initiate the date (YYYYMMDD) without dashes
declare #date varchar(10) = convert(int, convert(varchar(10), getdate(), 112))
--Execute the query with the variables resulting in a new table titled 'template_fields_20150909'
EXEC('select * into '+#table+'_'+#date+' from '+#table)

Resources