Dynamic table name and variable name in query in SQL Server - sql

I am trying to make a query that I can run from Python with dynamic table name and date. In the process of this, I have tried the following query in SSMS, but it is producing an error message. How can I use variables for table name and a date, and get the query to work?
DECLARE #table_name VARCHAR(50)='table_name';
DECLARE #valid_to datetime = getdate();
EXEC('UPDATE '+ #table_name + '
SET valid_flag = 0,
valid_to = '+ #valid_to +'
where valid_flag=1')
I get the following error message:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '10'

Use sp_executesql and parameters:
DECLARE #table_name VARCHAR(50) = 'table_name';
DECLARE #valid_to datetime = getdate();
DECLARE #sql NVARCHAR(max) = N'
UPDATE '+ #table_name + N'
SET valid_flag = 0,
valid_to = #valid_to
WHERE valid_flag = 1
';
EXEC sp_executesql #sql, N'#valid_to datetime', #valid_to=#valid_to;
EDIT:
As recommended by Larnu a comment:
DECLARE #table_name sysname = 'table_name';
DECLARE #valid_to datetime = getdate();
DECLARE #sql NVARCHAR(max) = N'
UPDATE '+ QUOTENAME(#table_name) + N'
SET valid_flag = 0,
valid_to = #valid_to
WHERE valid_flag = 1
';
EXEC sp_executesql #sql, N'#valid_to datetime', #valid_to=#valid_to;

Related

Passing a variable to a table name as a string [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

Dynamic Table name being recognised as a column name

Any reason why the dynamic schema and table name in the below script is being recognised as a column name? IF i hard code in the schema and table names outside of the dynamic script the function executes no issues.
Error = Msg 207, Level 16, State 1, Line 38
Invalid column name '55_Dataset'.
Msg 207, Level 16, State 1, Line 38
Invalid column name 'EPAPRIORITY'.
repeated for each iteration
Table example enter image description here
DECLARE #Counter INT;
DECLARE #DATASET nvarchar(50);
DECLARE #STATE nvarchar(50);
DECLARE #sql nvarchar(max);
SET #Counter = 1;
WHILE #Counter <= 10
BEGIN
SET #DATASET = (Select [DATASET] FROM [xxx].[dbo].[EPA_Geocoding_Progress] Where [INT] = #Counter)
SET #STATE = (Select [STATE] FROM [xxx].[dbo].[EPA_Geocoding_Progress] Where [INT] = #Counter)
SET #sql = '
UPDATE [xxx].[dbo].[EPA_Geocoding_Progress]
Set [Geocoded] = (Select COUNT (*) FROM [xxx].[' + #STATE + '].[' + #DATASET + '])
Where [STATE] = [' + #STATE + '] AND [DATASET] = [' + #DATASET + ']'
exec sp_executesql #sql;
SET #Counter = #Counter + 1;
END
If you will code with print like this:
declare #sql varchar(max)
declare #STATE varchar(50)
declare #DATASET varchar(50)
set #STATE = 'dbo'
set #DATASET = 'test'
Set #sql = '
UPDATE [dbo].[EPA_Geocoding_Progress]
Set [Geocoded] = (Select COUNT (*) FROM [' + #STATE + '].[' + #DATASET + '])'
print #sql;
you will see what's wrong.
SQL server Version
it seems no problem
check ; before Set
i try it:
CREATE TABLE EPA_Geocoding_Progress(
Geocoded int
);
CREATE TABLE TEST(
ID int
);
Declare #sql nvarchar(max) = ''
,#STATE nvarchar(max) = 'dbo'
,#DATASET nvarchar(max) = 'test'
Set #sql = '
UPDATE [dbo].[EPA_Geocoding_Progress]
Set [Geocoded] = (Select COUNT (*) FROM [' + #STATE + '].[' + #DATASET + '])'
select #sql
exec sp_executesql #sql; -- Run Success
DEMO SQL Fiddle

Change all empty strings to NULL using one query with loop. SQL

I have table with columns:
[1959], [1960], [1961] ... [2016];
All these columns are type nvarchar(255), some of these have empty strings ''. I want to change empty strings to NULL. I write query:
DECLARE #empty nvarchar(255);
SET #empty='';
DECLARE #cnt INT = 1959;
WHILE #cnt < 2017
BEGIN
declare #sql nvarchar(1000)
set #sql = 'UPDATE [HDProjEtap1Proba1].[dbo].[TESTGDP] SET [' + CAST(#cnt as nvarchar(255)) + '] = null WHERE ['+ CAST(#cnt as nvarchar(255)) +'] = ' + #empty;
EXEC(#sql);
SET #cnt = #cnt + 1;
END;
But dosn't work. Message error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.
Can you tell me how do it right?
#empty is empty. It doesn't represent the empty string when you concatenate it.
One simple solution is:
SET #empty = '''';
However, you can do the same thing by passing a parameter using sp_executesql. And I like that approach:
declare #cnt INT = 1959;
while #cnt < 2017
begin
declare #sql nvarchar(1000)
set #sql = 'UPDATE [HDProjEtap1Proba1].[dbo].[TESTGDP] SET [' + CAST(#cnt as nvarchar(255)) + '] = null WHERE ['+ CAST(#cnt as nvarchar(255)) +'] = #empty';
exec sp_executesql #sql, N'#empty nvarchar(255)', #empty = '';
set #cnt = #cnt + 1;
end;
Or event:
declare #cnt INT = 1959;
while #cnt < 2017
begin
declare #sql nvarchar(1000)
set #sql = '
UPDATE [HDProjEtap1Proba1].[dbo].[TESTGDP]
SET [#colname] = null
WHERE [#colname] = #empty';
set #sql = replace(#sql, '#colname', cast(#cnt as varchar(255));
exec sp_executesql #sql, N'#empty nvarchar(255)', #empty = '';
set #cnt = #cnt + 1;
end;
Notice that in this version, the SQL statement is easy to read (and hence to modify and debug). It is defined with parameters that are then subsequently replaced.

Why I can't set the value [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

Invalid column name when using sp_executesql

When I try to execute a dynamic query inside a stored procedure I'm getting an error.
My code is:
DECLARE #Query nvarchar(max)
DECLARE #AllowanceBadge nvarchar(20)
DECLARE #AllowFieldName nvarchar(50)
DECLARE #Amount Decimal
SET #AllowanceBadge ='SIP0980'
SET #AllowFieldName ='xxxxx'
SET #Amount = 100
SET #Query = 'UPDATE tbl_PayrollTransaction SET '+ #AllowFieldName +' = '+convert(varchar,#Amount) + 'WHERE BadgeNumber = '+#AllowanceBadge
EXEC SP_EXECUTESQL #Query
I'm getting following error
Msg 207, Level 16, State 1, Line 1
Invalid column name 'SIP0980'.
Tell me where I'm wrong.
Thanks
Need quotes around the SIP0890
DECLARE #Query nvarchar(max)
DECLARE #AllowanceBadge nvarchar(20)
DECLARE #AllowFieldName nvarchar(50)
DECLARE #Amount Decimal
SET #AllowanceBadge ='SIP0980'
SET #AllowFieldName ='xxxxx'
SET #Amount = 100
SET #Query = 'UPDATE tbl_PayrollTransaction SET '+ #AllowFieldName +' = '+convert(varchar,#Amount) + 'WHERE BadgeNumber = '''+#AllowanceBadge+''''
EXEC SP_EXECUTESQL #Query