I am creating a procedure in T-SQL:
CREATE PROCEDURE usp_QC1
AS
BEGIN
DECLARE #tablename varchar(100);
DECLARE #sfilename varchar(100);
DECLARE #rread varchar(100);
DECLARE #rwrite varchar(100);
DECLARE #sserver varchar(100);
DECLARE #dbname varchar(100);
DECLARE cur_tracking CURSOR FOR
SELECT
[TableName],
sfilename,
[RecordsRead],
[RecordsWritten],
[SQLServer],
[SQLDatabase]
FROM
[ADataTracker].[dbo].[TrackerLoadLog]
WHERE
LOWER(datagroup) LIKE '%Oracle RMS%'
AND SUBSTRING(sfilename, 1, 10) = '2022-03-16'
OPEN cur_tracking;
FETCH NEXT FROM cur_tracking INTO #tablename, #sfilename, #rread, #rwrite, #sserver, #dbname;
WHILE ##Fetch_status = 0
BEGIN
SELECT
sfilename, COUNT(*)
FROM
#sserver + '.dbo.' + #dbname
WHERE
sfilename = #sfilename
GROUP BY
sfilename
FETCH NEXT FROM cur_tracking INTO #tablename, #sfilename, #rread, #rwrite, #sserver, #dbname;
END;
CLOSE cur_tracking;
DEALLOCATE cur_tracking;
END
The cursor cur_tracking is holding the data (just showing 1 record)
---------------------------------------------------------------------------------------------------------------------------
TableName |sfilename | RecordsRead |RecordsWritten |SQLServer |SQLDatabase |
History |2022-03-16\20220316032322.dat| 5819560 |5819560 |a.stg.sql.ccaintranet.com |DataRms_Back |
So the cursor is having all the information of server, Databasename, tablename. I want to go to those each server.db.table and retrieve the information using these cursor elements:
SELECT sfilename, COUNT(*)
FROM #sserver + '.dbo.' + #dbname
WHERE sfilename = #sfilename
GROUP BY sfilename
But I get an error:
invalid column name sfilename
must declare the table variable #sserver
This is never going to work:
select sfilename,count(*) from #sserver+'.dbo.'+#dbname
You can't parameterize entity names like this (also database comes before schema, and you missed #tablename entirely).
Instead you can do:
DECLARE #sql nvarchar(max), #exec nvarchar(1000);
...
-- then inside the cursor:
SET #sql = N'select sfilename = #sfilename,count(*)
FROM dbo.' + QUOTENAME(#tablename)
+ N' WHERE sfilename = #sfilename;';
SET #exec = QUOTENAME(#dbname) + N'.sys.sp_executesql';
EXEC #exec #sql, N'#sfilename varchar(100)', #sfilename;
Note that all of these need to be nvarchar(128), and you can use the same DECLARE for multiple variables to lighten eye strain:
DECLARE #tablename nvarchar(128),
#sfilename nvarchar(128),
#dbname nvarchar(128);
Please review this collection of links.
Related
I need to get the max edit date for each table in our database and store in a temp table. The cursor works fine but when I run exec sp_executesql #sql I get a parameter expectation error:
Parameterized dynamic query within Cursor gives ERROR Procedure expects parameter '#params' of type 'ntext/nchar/nvarchar'
What am I doing wrong?
SET NOCOUNT ON
IF OBJECT_ID('tempdb..##GetMaxVistaEditDate') IS NOT NULL
DROP TABLE ##GetMaxVistaEditDate
CREATE TABLE ##GetMaxVistaEditDate
(
MySchema nvarchar(max),
MyTable nvarchar(max),
MaxVistaEditDate DateTime
)
-- SELECT * FROM ##GetMaxVistaEditDate
DECLARE MyCursor CURSOR FOR
SELECT
SCHEMA_NAME(t.schema_id) Schemaname,
t.name AS TableName
FROM
sys.tables t
WHERE
Schema_Name(t.Schema_id) like 'R_PERS%'
OPEN MyCursor
DECLARE #Schema VARCHAR(100), #Table VARCHAR(100), #MaxVistaEditDate DATETIME
DECLARE #sql NVARCHAR(MAX) = '', #params NVARCHAR(MAX);
SET #params = N'#MaxVistaEditDate DateTime OUTPUT';
FETCH FROM MyCursor INTO #Schema, #Table
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = 'DECLARE #MaxVistaEditDate DATETIME SELECT #MaxVistaEditDate = (SELECT MAX(VistaEditDate) FROM ' + #SCHEMA + '.' + #TABLE + ')'
EXEC sp_executesql #sql, #MaxVistaEditDate OUTPUT
-- PRINT #SQL
-- PRINT #MaxVistaEditDate
INSERT INTO ##GetMaxVistaEditDate
SELECT #Schema, #Table, #MaxVistaEditDate
FETCH FROM MyCursor INTO #Schema, #Table
END
CLOSE MyCursor
DEALLOCATE MyCursor
You don't have to declare the variables on the sql string, you have to do it on a different variable, and you already have one for that (you name it #params).
Change your #sql definition for the following
SET #SQL = 'Select #MaxVistaEditDate = (SELECT MAX(VistaEditDate) From ' + #SCHEMA + '.' + #TABLE + ')'
And change your call for this:
exec sp_executesql #sql ,#params, #MaxVistaEditDate = #MaxVistaEditDate OUTPUT
and it should work.
Note: Don't forget to close and deallocate the cursor.
you can find an answer in this post
SP_EXECUTESQL and Output Parameter
and your sp_executesql statement don't have parameter definition and you don't have to declare a variable inside the dynamic query
declare #MaxVistaEditDate datetime
exec sp_executesql #sql ,N'#MaxVistaEditDateOut datetime OutPut, #MaxVistaEditDateOut=#MaxVistaEditDate OUTPUT
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 have created a cursor which iterates through all the databases and displays the 1 record per database.
I would like the records to be inserted into 1 table where I can view it. The query may change which is why I don't want to create the table structure for a specific query and insert it. I wanted to use the "select into" clause but that will fail on the second time the cursor runs
DECLARE #DB_Name varchar(100)
DECLARE #Command nvarchar(200)
DECLARE database_cursor CURSOR FOR SELECT name FROM #DBNAME
OPEN database_cursor
FETCH NEXT FROM database_cursor INTO #DB_Name
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #Command = 'use [' + #DB_Name + '] Select '''+ #DB_Name + ''' ,'+
--Enter query below
'* from authentication where username like ''%clair#indicater%'' and password = ''Rohan2410'''
-- print #Command
EXEC sp_executesql #Command
FETCH NEXT FROM database_cursor INTO #DB_Name
END
CLOSE database_cursor
DEALLOCATE database_cursor
You should better use INSERT INTO ... instead of SELECT INTO, something like this:
DECLARE #DB_Name varchar(100)
DECLARE #Command nvarchar(200)
DECLARE database_cursor CURSOR FOR SELECT name FROM #DBNAME
OPEN database_cursor
FETCH NEXT FROM database_cursor INTO #DB_Name
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #Command = 'use [' + #DB_Name + ']
IF OBJECT_ID(''tempdb..##output'') IS NULL
BEGIN
SELECT NULL AS DB_Name,*
INTO ##output
FROM authentication WHERE 1=0
END
INSERT INTO ##output
Select '''+ #DB_Name + ''' ,'+
--Enter query below
'* from authentication where username like ''%clair#indicater%'' and password = ''Rohan2410'''
-- print #Command
EXEC sp_executesql #Command
FETCH NEXT FROM database_cursor INTO #DB_Name
END
CLOSE database_cursor
DEALLOCATE database_cursor
SELECT * FROM ##output
DROP TABLE ##output
Basically, on the first cursor iteration we will create an empty temp table with the correct structure. Then we just insert into that temp table.
I have a query that I want to be able to use across database schemas. Right now it is written so that I need to replace the schema in several places of the query. How do I set that up as a variable so that all I need to do is change it in one place?
You can do this with Dynamic SQL:
DECLARE #sql VARCHAR(MAX)
,#schema VARCHAR(255) = 'dbo'
SET #sql = 'SELECT *
FROM '+#schema+'.yourTable
'
EXEC (#sql)
You could use this in a cursor to loop through schema's:
DECLARE #Iterator varchar(255)
,#strSQL varchar(MAX)
DECLARE xyz CURSOR
FOR
--Select stuff to iterate over
SELECT name
FROM sys.schemas
OPEN xyz
FETCH NEXT FROM xyz
INTO #Iterator
WHILE ##FETCH_STATUS = 0
BEGIN
--Do stuff
SET #strSQL = 'SELECT *
FROM '+#Iterator+'.yourTable
'
Exec (#strSQL)
FETCH NEXT FROM xyz
INTO #Iterator
END
CLOSE xyz
DEALLOCATE xyz
GO
To test your dynamic SQL statements, you can change EXEC to PRINT and ensure that the resulting query is as you intended.
Synonyms might be the answer to your question.
You can use dynamic SQL. Here is an example -
DECLARE #Column varchar(25)
DECLARE #sqlStmt varchar(max)
SET #Column = 'MyColumn'
SET #sqlStmt = N'SELECT ' + #Column + ' FROM MyTable'
EXEC (#sqlStmt)
Say I want to run the following:
update users set age = 10
on databases:
db1, db2, db3
All on the same server, I want to loop through and perform the same action.
Currently I am doing this manually using management studio via the dropdown.
Hoping there is a better way.
You could probably do it with dynamic SQL. Something like so:
create table #dbs (db_name sysname not null)
insert into #dbs values ('db1'),('db2'),('db3')
declare curs cursor for
select db_name from #dbs
declare #db sysname, #sql nvarchar(max)
open curs
while(1=1)
begin
fetch next from curs into #db
if (##fetch_status <> 0)
break
set #sql = 'update ' + quotename(#db) + '.dbo.users set age = 10'
exec(#sql)
end
close curs
deallocate curs
drop table #dbs
Not sure about doing it 'dynamically', i.e. a FOR-EACH style loop on all the databases in a server, but this should work:
USE db1
update users set age = 10
GO
USE db2
update users set age = 10
GO
USE db3
update users set age = 10
Designate a server as a central management server and then add the other servers to the server group. Then you can run the update on all databases within the group. http://msdn.microsoft.com/en-us/library/bb934126.aspx
use [WWAUTHxxx__] -- a db containing active databases.
set nocount on
declare #Catalog as nvarchar(32)
declare #LibraryName as varchar(255)
declare #dbtable as varchar(50)
declare #retval as nvarchar(50)
declare #sSQL as nvarchar(max)
declare #parmdef as nvarchar(500)
declare #retvalout as nvarchar(50)
Declare Library_Cursor Cursor for
select top(1000) xCatalog, xLibraryName
from Active_DBs
order by xcatalog
Open Library_Cursor;
Fetch Next from Library_Cursor into #Catalog, #LibraryName
while ##Fetch_status = 0
begin
set #dbTable = #Catalog + '.dbo.las_circperiods'
set #ParmDef = N'#retvalOUT int OUTPUT';
set #sSQL = N'Select #retvalout = count(*) from ' + #dbtable
+ ' where xlastcircdate is null'
exec sp_executesql #ssql,#parmdef,#retvalout=#retval output
if #retval > 0 -- check/print Sql and then activate.
-- I like checking to see the potentially affected databases.
begin
print #Catalog + ',' + #LibraryName + ',' + #retval
set #ssql = N'update ' + #dbTable
+ ' set xlastcircdate = '''' '
+ ' where xlastcircdate is null'
-- print #ssql -- View what you might will do
exec sp_executesql #ssql -- Do it.
end
Fetch Next from Library_Cursor into #Catalog, #LibraryName
end;
close Library_cursor
Deallocate Library_cursor