I have this SQL code that I'm using to insert 3 tables at a time dynamically. When I try to run it, I get this message
Msg 137, Level 16, State 1, Procedure InsertData, Line 28
Must declare the scalar variable "#RECEIVABLESDATA".
Any ideas?
USE [PantaRei]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertData]
#RECEIVABLESDATA RECEIVABLESTABLE READONLY,
#DILUTIONSDATA DILUTIONSTABLE READONLY,
#ACCOUNTABLESDATA ACCOUNTABLESTABLE READONLY,
#TABLE1 VARCHAR(MAX),
#TABLE2 VARCHAR(MAX),
#TABLE3 VARCHAR(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
DECLARE #CMD nvarchar(345)
SET NOCOUNT ON;
SET #TABLE1 = RTRIM(#TABLE1)
SET #TABLE2 = RTRIM(#TABLE2)
SET #TABLE3 = RTRIM(#TABLE3)
SET #CMD =
'INSERT INTO ' + QUOTENAME(#TABLE1) +
'SELECT * FROM [DBO].' + QUOTENAME(#RECEIVABLESDATA)
EXECUTE sp_executesql #CMD
SET #CMD =
'INSERT INTO ' + QUOTENAME(#TABLE2) +
'SELECT * FROM [DBO].' + QUOTENAME(#DILUTIONSDATA)
EXECUTE sp_executesql #CMD
SET #CMD =
'INSERT INTO '+ QUOTENAME(#TABLE3) +
'SELECT * FROM [DBO].' + QUOTENAME(#ACCOUNTABLESDATA)
END
Try to use temp tables:
SELECT * INTO #t1 FROM #RECEIVABLESDATA;
SET #CMD =
'INSERT INTO ' + QUOTENAME(#TABLE1) +
'SELECT * FROM #t1';
EXECUTE sp_executesql #CMD
Also here is the other way. Check if it works in your MS SQL version:
SET #CMD =
'INSERT INTO ' + QUOTENAME(#TABLE1) +
'SELECT * FROM #RECEIVABLESDATA';
EXECUTE sp_executesql #CMD, N'#RECEIVABLESDATA RECEIVABLESDATA READONLY', #RECEIVABLESDATA;
Related
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
I use dynamic sql to create database an tables
this is sql script
DECLARE #DatabaseName VARCHAR(50) = N'test';
EXECUTE ('CREATE DATABASE [' +#DatabaseName+']');
EXECUTE('USE ' + #DatabaseName)
GO
CREATE SCHEMA [Framework]
GO
the error I get
Msg 2714, Level 16, State 6, Line 1
There is already an object named 'Framework' in the database.
Msg 2759, Level 16, State 0, Line 1
CREATE SCHEMA failed due to previous errors
.
this error because EXECUTE('USE ' + #DatabaseName) not work
I try to use
SET #SQL02 = 'USE ['+ convert(nvarchar(50),#DatabaseName) +']; SELECT DB_NAME();'
exec sp_executesql #SQL02
but not work
what I can do?
DECLARE #Query VARCHAR(200);
SET #Query = CONCAT('USE ', QUOTENAME('<MyDatabase>'), '; ', 'select DB_NAME();');
EXECUTE (#Query);
This will return <MyDatabase> as long as you remain within one EXECUTE.
I prefer this form for remote execution:
declare #sql nvarchar(max) = N'select Db_Name()';
<DatabaseName>.sys.sp_executesql #sql;
You can put this logic into a more convenient form by making into a stored procedure:
create procedure dbo.usp_ExecuteSqlCommand (
#databaseName sysname
, #sqlCommand nvarchar(max)
)
as
begin;
set nocount on;
set xact_abort on;
declare #innerStatement nvarchar(max) = #sqlCommand;
declare #outerStatement nvarchar(max);
set #databaseName = QuoteName(ParseName(#databaseName, 1), N'[');
set #outerStatement = #databaseName + N'.sys.sp_executesql #stmt = #innerStatement;';
execute sys.sp_executesql
#stmt = #outerStatement
, #params = N'#innerStatement nvarchar(max)'
, #innerStatement = #innerStatement;
end;
Usage is obvious:
execute dbo.usp_ExecuteSqlCommand
#databaseName = N'master'
, #sqlCommand = N'select Db_Name();';
Try this:(if you use execute, the db context will change only for that execute only)
DECLARE #DatabaseName VARCHAR(50) = N'test';
EXECUTE ('CREATE DATABASE [' +#DatabaseName+']');
use [test]
go
CREATE SCHEMA [Framework]
GO
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
I am totally confused with this procedure.please correct my mistakes in quotes.
create procedure queryingsfor
#Tabname nvarchar(250),
#colname nvarchar(250),
#opname nvarchar(290),
#valuesname nvarchar(239)
as
begin
set NOCOUNT on;
declare #sql varchar(4000)
set #sql='select * from' +#Tabname+ 'where' +#colname+''''+#opname+''''+ ''''+#valuesname+''''
exec(#sql)
end
exec queryingsfor 'education','eduCurrentStudy','=','DME'
I'm only getting:
Error: Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'fromeducationwhereeduCurrentStudy'.
You might want to add some spaces in there
set #sql='select * from ' +#Tabname+ ' where '
+#colname+''''+#opname+''''+ ''''+#valuesname+''''
The correct statement would be something like
set #sql='select * from ' +#Tabname+ ' where '
+#colname + #opname+ ''''+#valuesname+''''
Or
even better
set #sql='select * from [' +#Tabname+ '] where
[' +#colname + ']' + #opname+ ''''+#valuesname+''''
To protect you from SQL injection you should do like this instead.
alter procedure queryingsfor
#Tabname nvarchar(250),
#colname nvarchar(250),
#opname nvarchar(4),
#valuesname nvarchar(239)
as
begin
set NOCOUNT on;
declare #sql nvarchar(4000)
set #sql = 'select * from '+quotename(#Tabname)+ ' where ' +quotename(#colname)+#opname+'#valuesname'
exec sp_executesql #sql, N'#valuesname nvarchar(239)', #valuesname
end
I keep getting an error with the following stored procedure. I had it working correctly using EXEC, then I switched to sp_executesql and I haven't been able to get it to execute. I keep getting the following error: Incorrect syntax near '#numberOfItems'.
ALTER PROCEDURE dbo.FetchResourcesToProcess
(
#tableName nvarchar(MAX),
#numberOfItems int
)
AS
BEGIN
DECLARE #SQL nvarchar(MAX);
SET NOCOUNT ON;
SET #SQL = N'Select TOP #numberOfItems * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
EXEC sp_executesql #SQL, N'#numberOfItems int', #numberOfItems
END
Tablename is a string structured as follows: "[TABLENAME]".
Thanks
You probably need to place number of items into the string the same way you are the table name
SET #SQL = N'Select TOP ' + Convert(varchar(10),#numberOfItems) + ' * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
I think you can only use parameters for sp_executesql statement in positions where variables are allowed.
use master;
declare #numberOfItems int;
set #numberOfItems = 2;
Select TOP #numberOfItems * from dbo.spt_values
Incorrect syntax near '#numberOfItems'.
use master;
declare #table varchar(max);
set #table = 'dbo.spt_values';
Select * from #table
Must declare the table variable "#table".
use master;
declare #numberOfItems int;
set #numberOfItems = 2;
Select TOP(#numberOfItems) * from dbo.spt_values
(2 row(s) affected)
Solution 1 (parenthesis, recommended):
SET #SQL = N'Select TOP(#numberOfItems) * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
Solution 2 (concatenation, make sure to prevent SQL injection!):
SET #SQL = N'Select TOP '+cast(#numberOfItems as nvarchar(MAX))+' * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
EXEC sp_executesql #SQL