Invalid variable - sql

This stored procedure works until I add in a variable. The #sWHERE variable will be populated from a a fixed input.
I'm not sure what I need to amend ...I've tried adding & and +
Error: 4145, Level 15, State 1, Procedure spUniqueUPRN, Line 12 An expression of non-boolean type specified in a context where a
condition is expected, near 'Group'.
Stored Procedure:
USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUniqueUPRN]
#sWHERE varchar(Max)
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT UPRN INTO TBLTEMP FROM TblA
WHERE #sWHERE
Group BY UPRN
UNION ALL
SELECT UPRN FROM TblP
Group BY UPRN
END
VERSION 2 based on help so far (no where near final just a step)
USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUniqueUPRN]
#sWHERE varchar(Max)
AS
BEGIN
SET NOCOUNT ON;
----------
DROP TABLE TBLTEMP
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = 'UPRN INTO TBLTEMP FROM TblA ' + QUOTENAME(#sWHERE) + '
Group BY UPRN
UNION ALL
SELECT UPRN FROM TblP
Group BY UPRN
';
EXEC sp_executesql #SQL;
----------
END
Verion 3
USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER PROCEDURE [dbo].[spUniqueUPRN]
#sDateFrom Date,
#sDateTo Date,
#sUPRN varchar(Max),
#sRiskRating varchar(10),
#sSurveyCompany varchar(Max),
#sPostcode varchar(10),
#sStreet varchar(Max),
#sRegion Int
AS
BEGIN
SET NOCOUNT ON;
----------
DROP TABLE TBLTEMP
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = 'SELECT UPRN INTO TBLTEMP FROM TblA WHERE 1 = 1 '
IF QUOTENAME(#sDateFrom) IS NOT NULL AND QUOTENAME(#sDateTo) IS NOT NULL
SELECT #SQL = #SQL + ' or SurveyDate BETWEEN ' + QUOTENAME(#sDateFrom) + ' AND ' + QUOTENAME(#sDateTo) + ''''
IF QUOTENAME(#sRiskRating) IS NOT NULL
SELECT #SQL = #SQL + ' or OverAllRiskCategory = ' + QUOTENAME(#sRiskRating) +''''
IF QUOTENAME(#sUPRN) IS NOT NULL
SELECT #SQL = #SQL + ' or UPRN LIKE ' + QUOTENAME(#sUPRN) + ''''
IF QUOTENAME(#sSurveyCompany) IS NOT NULL
SELECT #SQL = #SQL + ' or SurveyCompany LIKE ''%' + QUOTENAME(#sSurveyCompany) + '%'''
SELECT #SQL = #SQL + ' GROUP BY UPRN '
SELECT #SQL = #SQL + ' UNION ALL '
SELECT UPRN FROM TblProperty
IF QUOTENAME(#sPostcode) IS NOT NULL
SELECT #SQL = #SQL + ' or Postcode LIKE ''%' + QUOTENAME(#sPostcode) + '%'''
IF QUOTENAME(#sStreet) IS NOT NULL
SELECT #SQL = #SQL + ' or Street LIKE ''%' + QUOTENAME(#sStreet) + '%'''
IF QUOTENAME(#sRegion) IS NOT NULL
SELECT #SQL = #SQL + 'or Region LIKE ''%' + QUOTENAME(#sRegion) + '%'''
SELECT #SQL = #SQL + 'GROUP BY UPRN'
EXEC sp_executesql #SQL;
----------
END

First of all to pass #sWHERE as string to stored procedure you need to use dynamic SQL.
Before you use dynamic SQL I strongly recommend to read The Curse and Blessings of Dynamic SQL by Erland Sommarskog.
Your case is SELECT * FROM tbl WHERE #condition:
If you are considering to write the procedure
CREATE PROCEDURE search_sp #condition varchar(8000) AS
SELECT * FROM tbl WHERE #condition
Just forget it. If you are doing this, you have not completed the transition to use stored procedure and you are still assembling your
SQL code in the client. But this example lapses into Dynamic Search Conditions/Dynamic Crosstab.
The point is that you could use (as proposed in comments)
DECLARE #sql NVARCHAR(MAX) =
N'SELECT *
FROM table_name
WHERE ' + #sWHERE;
EXEC dbo.sp_executesql
#sql;
But this is straight way to SQL Injection attacks. User may call:
EXEC dbo.spUniqueUPRN '1=1; DROP TABLE ....; --'
To sum up, it is up to you if you will use WHERE #condition. It is possible but I would not go this path.

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 / parametrized stored procedure in SQL Server [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

Sql server using a built int function in a stored procedure

I am trying to write a SP that uses the substring function inside a stored procedure where I use the column name as input. However when I run
exec sp_addCountySchoolDistrict N'table', N'districtCountySchoolCode'
It uses the 'districtCountySchoolCode' for the substring and not the value from the row...
For example
create table [dbo].[test] (districtCountySchoolCode nvarchar(100))
insert into dbo.test values ('1234567891234')
go
CREATE PROCEDURE sp_addCountySchoolDistrict
#tableName nvarchar(100),
#colName nvarchar(100)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql NVARCHAR(MAX);
SET #Sql= N'alter table ' + replace(replace(quotename(#tableName),']',''),'[','') +
N' add countyCode as ''' + substring(#colName, 1,2) + N',
districtCode as ''' + substring(#colName, 3,5) + N',
schoolCode as ''' + substring(#colName, 8,7) + N';'
select #sql;
EXECUTE sp_executesql #Sql
END
GO
exec sp_addCountySchoolDistrict N'[dbo].[test]', N'districtCountySchoolCode'
select * from test_copy
Coder Wall
Put the substring in the literal part of the dynamic sql, like this:
N' add countyCode as substring(''' + #colName+ N', 1,2) ,
try this
exec sp_addCountySchoolDistrict N'[dbo].[test]', N'1234567891234'
Your mistake is that you pass the "column name" as a string but your code nowhere selects the value from test table for the specified column. You have to perform a select statement first, to get the value and then use the value in the rest code.
This should work
create table [dbo].[test] (districtCountySchoolCode nvarchar(100))
insert into dbo.test values ('1234567891234')
go
CREATE PROCEDURE sp_addCountySchoolDistrict
#tableName nvarchar(100),
#colName nvarchar(100)
AS
BEGIN
declare #val nvarchar(100);
declare #initialQuery nvarchar(100);
SET NOCOUNT ON;
DECLARE #Sql NVARCHAR(MAX);
SET #initialQuery = 'SELECT #value=' + quotename(#colName) + ' FROM ' + replace(replace(quotename(#tableName),']',''),'[','')
EXECUTE sp_executesql #initialQuery, N'#value nvarchar(100) OUTPUT', #value=#val OUTPUT
SET #Sql= N'alter table ' + replace(replace(quotename(#tableName),']',''),'[','') +
N' add countyCode as ''' + substring(#val, 1,2) + N''',
districtCode as ''' + substring(#val, 3,5) + N''',
schoolCode as ''' + substring(#val, 8,7) + N''';'
select #sql;
EXECUTE sp_executesql #Sql
END
GO
exec sp_addCountySchoolDistrict N'[dbo].[test]', N'districtCountySchoolCode'
select * from test
But you have to add a where condition i suppose if you have more than one values in test table.

Returning passed parameter as column in result set

I have the following stored procedure code working and want to add the passed parameter #tabname as a column in the result set.
CREATE PROCEDURE CountStar
#Tabname char(10)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL varchar(250)
SELECT #SQL = 'SELECT ETL_LAST_UPD_DTTM, COUNT(*) FROM ls.' + QuoteName(#Tabname) +
'GROUP BY ETL_LAST_UPD_DTTM'
EXEC (#SQL)
SELECT #SQL = 'SELECT ETL_LAST_UPD_DTTM, COUNT(*) FROM ci.' + QuoteName(#Tabname) +
'GROUP BY ETL_LAST_UPD_DTTM'
EXEC (#SQL)
--COMMIT
END
GO
Currently this will return the last updated timestamp and the record count for the table being passed into the stored procedure for the 2 schemas identified. I want to add the #tabname to the result set as the first column followed by last updated timestamp and the record counts. This returns 2 result sets and each should look something like this for each returned result set.
Table_name Timestamp rec_cnt
--------------------------------------------------
CUSTOMERS 2015-09-24 13:10:01.1770000 378
I have tried a few things but can't get the syntax correct.
Thanks for any pointers.
Pat
CREATE PROCEDURE CountStar
#Tabname SYSNAME --<-- use appropriate data type for sql server objects
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL nvarchar(max);
SELECT #SQL = N'SELECT #Tabname AS Table_name,ETL_LAST_UPD_DTTM, COUNT(*)
FROM ls.' + QuoteName(#Tabname) +
N' GROUP BY ETL_LAST_UPD_DTTM'
EXEC sp_executesql #SQL
,N'#Tabname SYSNAME'
,#Tabname
SELECT #SQL = N'SELECT #Tabname AS Table_name,ETL_LAST_UPD_DTTM, COUNT(*)
FROM ci.' + QuoteName(#Tabname) +
N' GROUP BY ETL_LAST_UPD_DTTM'
EXEC sp_executesql #SQL
,N'#Tabname SYSNAME'
,#Tabname
END
GO

Getting a table name in a Stored Procedure and using it later [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