Select from table with dynamic compute name - sql

I want to write query in which name table will dynamicaly compute. I have code like this below. What should I put in 'magic code' region?
DECLARE #myTableName nvarchar(100) = 'sch'
+ CAST(#nowYear as VARCHAR(5))
+ 'Q'
+ CAST(#nowQuarter as VARCHAR(3))
+ '.[tVisits]'
-- magic code --
myTable = DoSomething(#aktTableName)
-- magic code --
SELECT * FROM myTable
I use MS SQL Server 2012

You need use the dynamic SQL -
DECLARE
#nowYear INT = 2013
, #nowQuarter INT = 1
DECLARE #myTableName NVARCHAR(100) = '[sch'
+ CAST(#nowYear AS VARCHAR(5))
+ 'Q'
+ CAST(#nowQuarter AS VARCHAR(3))
+ '].[tVisits]'
DECLARE #SQL NVARCHAR(MAX) = N'SELECT * FROM ' + #myTableName
EXEC sys.sp_executesql #SQL

Instead of SELECT * FROM myTable
You need to do something like
DECLARE #sql nvarchar(4000)
SELECT #sql = ' SELECT * FROM ' + #myTable -- #myTable is a string containing qualified table name
EXEC sp_executesql #sql
Note that sp_executesql allows for a parameterized query - check its documentation

Related

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 Dynamic SQL - Get output from list of tables

I am trying to loop through a temp table variable that contains a list of table names. I want to simply count the rows in each table where a DateTracked column is greater than 30 days. I am having trouble dynamically changing the FROM #tblName variable to store the record count and then insert it into my tracking table. Eventually I will use a cursor to loop through each, but I just want to get this logic down first for a single table. Here is my test code:
DECLARE #tblName as NVARCHAR(MAX)
DECLARE #q as NVARCHAR(MAX)
SET #q = 'Select Count(DateTracked) FROM Audit.' + #tblName + ' WHERE DateTracked > DATEADD(dd, -30, CAST(GETDATE() as date))'
--DECLARE #tblNameTable TABLE
--(
-- tableName NVARCHAR(MAX)
--)
--INSERT INTO #tblNameTable VALUES (N'myTestTable')
DECLARE #ExpectedRecordsToMove AS TABLE (col1 int)
INSERT INTO #ExpectedRecordsToMove EXECUTE sp_executesql #q, N'#tblName nvarchar(500)', #tblName = 'myTestTable'
SELECT * FROM #ExpectedRecordsToMove
Found solution.
DECLARE #tblName as NVARCHAR(MAX) = 'tblAutoDispatch_DispatchStatus_Map_Tracking'
DECLARE #q as NVARCHAR(MAX) = 'SELECT Count(DateTracked) FROM Audit.' + #tblName + ' WHERE DateTracked > DATEADD(dd, -30, CAST(GETDATE() as date))'
DECLARE #ExpectedRecordsToMove TABLE
(
ExpectedRecordsToMove Int
)
INSERT INTO #ExpectedRecordsToMove
EXECUTE sp_executesql #q
SELECT * FROM #ExpectedRecordsToMove
Note: Answer provided by OP on question.
sp_executesql also allows for output parameters. It is possible to assign variable inside the inner query and return the value.
DECLARE #tblName AS NVARCHAR(MAX) = N'tblAutoDispatch_DispatchStatus_Map_Tracking';
DECLARE #q AS NVARCHAR(MAX)
= N'SELECT #rowcount = COUNT(DateTracked) FROM Audit.' + #tblName
+ N' WHERE DateTracked > DATEADD(dd, -30, CAST(GETDATE() as date))';
DECLARE #rowcount INT;
EXECUTE sp_executesql
#query = #q,
#parameters = N'#rowcount INT OUTPUT',
#rowcount = #rowcount OUTPUT;
SELECT
#rowcount;
You can actually do this without a cursor, by building up the query in one go
You must use QUOTENAME to ensure table names do not cause syntax errors
You cannot parameterize a table name, it must be inserted directly into dynamic SQL
DECLARE #tablenames TABLE (schemaName sysname, tblName sysname);
-- insert schema and table names
DECLARE #sql nvarchar(max) = N'
SELECT
ISNULL(tblName, ''Grand Total'') AS tblName,
SUM(rowcount) AS rowcount
FROM (
' +
(
SELECT STRING_AGG(CAST(
N' SELECT ' + QUOTENAME(tn.schemaName, '''') + N'.' + QUOTENAME(tn.tblName, '''') + N' AS tblName,
Count(DateTracked) AS rowCount
FROM ' + QUOTENAME(tn.schemaName) + N'.' + QUOTENAME(tn.tblName) + N'
WHERE DateTracked > DATEADD(dd, -30, CAST(GETDATE() as date))'
AS nvarchar(max)), N'
UNION ALL
')
FROM #tablenames tn
JOIN sys.tables t ON tn.schemaName = SCHEMA_NAME(t.schema_id) AND tn.tblName = t.name
) + N'
) AS tables
GROUP BY ROLLUP(tblName);
';
PRINT #sql; -- for testing
EXEC (#sql);
If you don't have STRING_AGG on your version of SQL Server, you must use FOR XML instead

Assign result from dynamic SQL in a parameter to another parameter

I'm having to build my query dynamically, firstly, it gets the maxlogid from the log, and appends this to the temporary table name. Then it does a COALESCE to return the distinct values into a string.
However, the output of the string, I want to have in a parameter, so I can use it again later on within a dynamic sql query.
Here is my code;
DECLARE #maxLogId VARCHAR(10)
SELECT #maxLogId = (SELECT Max(id) FROM dbo.tLog)
DECLARE #PolicyTempTable VARCHAR(100)
SET #PolicyTempTable = '##tPols' + #maxLogId
DECLARE #emailParm NVARCHAR(1000)
SET #emailParm = N'DECLARE #email VARCHAR(MAX)
SELECT COALESCE(#email+'','' ,'''') + '''''''''''' + EMAIL + ''''''''''''
FROM (SELECT DISTINCT EMAIL FROM ' + #PolicyTempTable + ') d'
EXEC sp_executesql #emailParm
The results are returned as follows;
"abc#a.co.uk",""abc#b.co.uk"
I want to be able to write the sp_executesql into a seperate parameter, so I can use for a dynamic query like below;
DECLARE #StrSQLEmail VARCHAR(8000)
SET #StrSQLEmail = 'SELECT * FROM OPENQUERY(ATOM,''Select * from ATOMS.EMAILS WHERE EMAIL IN (' + '' EXEC sp_executesql #emailParm + '' + ')'')'
However, I can't use the sp_executesql within my dynamic query.
You can use parameters with sp_executesql
DECLARE #emailParm NVARCHAR(1000)
DECLARE #emailOut NVARCHAR(MAX)
SET #emailParm = N'SELECT COALESCE(#email+'','' ,'''') + '''''''''''' + EMAIL + ''''''''''''
FROM (SELECT DISTINCT EMAIL FROM ' + #PolicyTempTable + ') d'
EXEC sp_executesql #emailParm, N'#email VARCHAR(1000) OUTPUT', #email = #emailOut OUTPUT
Then you can build your second dynamic sql
DECLARE #StrSQLEmail VARCHAR(8000)
SET #StrSQLEmail = 'SELECT * FROM OPENQUERY(ATOM,''Select * from ATOMS.EMAILS WHERE EMAIL IN (' + #emailOut + ')'')'

How to form a table name from concatenating strings in Select Statement in SQL 2012

I want to achieve this -
SELECT * FROM A1234
I have the the ID 1234 saved in another table called Aliases which has two columns Alias,ID with one record like this.
Alias = TestTable, ID = 1234
So I am trying something like this
SELECT * FROM ('A'+ (SELECT ID FROM Aliases WHERE Alias = 'TestTable'))
Any help would be appreciated
You should use dynamic sql.
DECLARE #Q VARCHAR(MAX),#ID INT
SET #ID=(Select DISTINCT ID from Aliases where Alias = 'TestTable') -- CHECK TO RETURN JUST ON RESULT
SET #Q='SELECT * FROM A'+CAST(#ID AS VARCHAR(10))
EXEC(#Q)
You need dynamic SQL for this.
DECLARE #sql NVARCHAR(MAX);
SELECT TOP (1) #sql = N'SELECT * FROM A' + RTRIM(ID) + ';'
FROM dbo.Aliases WHERE Alias = 'TestTable';
EXEC sp_executesql #sql;
To build a set of statements that selects all of them, you can say:
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'';
SELECT #sql = #sql + N'
SELECT *, ''A' + RTRIM(ID) + ''' FROM A' + RTRIM(ID) + ';'
FROM dbo.Aliases;
PRINT #sql;
-- EXEC sp_executesql #sql;

Must declare the scalar variable with Table-Valued Parameters and Stored Procedure

Could someone explain why the following gives me "Must declare the scalar variable #facilities." but works fine if I were to use VARCHAR instead of my created type? How can I fix this?
TIA
--CREATE TYPE integer_list AS TABLE (n int NOT NULL PRIMARY KEY)
--DROP PROCEDURE spTestTVP
CREATE PROCEDURE spTestTVP (
#facilities integer_list READONLY
--#facilities varchar(100)
)
AS
DECLARE #sql nvarchar(4000)
SET #sql = 'SELECT * FROM TestTable'
SET #sql = #sql + ' WHERE 1=1 '
IF #facilities IS NOT NULL
SET #sql = #sql + ' AND (FacilityNo IN (' + #facilities + ') OR FacilityNo IS NULL)'
EXEC sp_executesql #sql
DECLARE #items VARCHAR(MAX)
SELECT#items = COALESCE(#items+',' ,'') + n
FROM #facilities
DECLARE #sql nvarchar(4000)
SET #sql = 'SELECT * FROM TestTable'
SET #sql = #sql + ' WHERE 1=1 '
IF #facilities IS NOT NULL
SET #sql = #sql + ' AND (FacilityNo IN (' + #items + ') OR FacilityNo IS NULL)'
EXEC sp_executesql #sql
or not dynamic as follows:
SELECT t.* FROM TestTable as t
left outer join
#facilities as f
on
f.n = t.FacilityNo
where
t.FacilityNo is null
or
f.n is not null
When you are concatenating things in a dynamicSQl statment all pieces that build the statement must be either varchar or nvarchar. That is a limit of SQL.
On the other hand you don't need dynamic sql since you have created a table.
SELECT * FROM TestTable t
LEFT join #facilities f on f.n = t.facilityNO