I have a list of employee names, and a list of tables. I need to iterate all employee names and find which table(s) the employee name exists in. All of the tables to iterate exist on the same server and the same database.
Sample data structure
Create Table TableNamesToCheck (dbName varchar(15))
Insert Into TableNamesToCheck
Values ('table1'), ('table2'), ('table3'), ('table4'), ('table5'),
('table6'), ('table7'), ('table8'), ('table9'), ('table10')
Create Table EN (employeename varchar(100))
Insert Into EN
Values ('Richard Marx'), ('Joseph Jones'), ('Mark Badcock'),
('Frank Fins'), ('Richard James'), ('Fall Fren'), ('Hiu Hen')
Thank you #Giorgi --- I understand using Cursor for my tablenames, but how do I join the two tables, when their is no similar field to join the 2 tables on? This is what I have (work in progress) if I understand what you are explaining this is my syntax, but it gives me the below error for each employee and each table...
Msg 207, Level 16, State 1, Line 1
Invalid column name 'employeename'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Richard'.
Declare #dbname varchar(25), #empname varchar(100), #sql varchar(Max)
Create Table TableNamesToCheck (dbName varchar(15))
Insert Into TableNamesToCheck
Values ('table1'), ('table2'), ('table3'), ('table4'), ('table5'),
('table6'), ('table7'), ('table8'), ('table9'), ('table10')
Create Table EN (employeename varchar(100))
Insert Into EN
Values ('Richard Marx'), ('Joseph Jones'), ('Mark Badcock'),
('Frank Fins'), ('Richard James'), ('Fall Fren'), ('Hiu Hen')
Declare c1 Cursor For
Select dbname
From TableNamesToCheck
Open c1
Fetch Next from c1 into #dbname
Declare c2 Cursor For
Select employeename
From EN
Open c2
Fetch Next from c2 into #empname
While ##FETCH_STATUS = 0
Begin
While ##FETCH_STATUS = 0
Begin
Set #sql = 'Select '+#dbname+' From TableNamesToCheck where employeename IN (Select '+#empname+' from EN)'
Exec (#sql)
Fetch Next From c1 Into #dbname
Fetch Next From c2 Into #empname
End
End
Close c1
Close c2
Deallocate c1
Deallocate c2
Drop Table TableNamesToCheck
Drop Table EN
Not 100% sure, but you might be looking for this :-
Set Nocount On;
Declare #Sql Varchar(Max)
,#Total Int
,#RowId Int
,#EmpName Varchar(100)
,#Total2 Int
,#RowId2 Int
,#TableName Varchar(15)
Select #Sql = ''
,#EmpName = ''
,#TableName = ''
If Object_Id('tempdb.dbo.#TableNamesToCheck') Is Not Null
Begin
Drop Table #TableNamesToCheck;
End
If Object_Id('tempdb.dbo.#EN') Is Not Null
Begin
Drop Table #EN;
End
If Object_Id('tempdb.dbo.#EnTables') Is Not Null
Begin
Drop Table #EnTables;
End
Create Table #TableNamesToCheck
(
dbId Int Identity(1,1) Primary Key
,dbName Varchar(15)
)
Create Table #EN
(
RowId Int Identity(1,1) Primary Key
,employeename Varchar(100)
)
Create Table #EnTables
(
Id Int Identity(1,1) Primary Key
,EmployeeName Varchar(100)
,dbName Varchar(15)
)
Insert Into #TableNamesToCheck
Values ('table1'), ('table2'), ('table3'), ('table4'), ('table5'),
('table6'), ('table7'), ('table8'), ('table9'), ('table10')
Insert Into #EN
Values ('Richard Marx'), ('Joseph Jones'), ('Mark Badcock'),
('Frank Fins'), ('Richard James'), ('Fall Fren'), ('Hiu Hen')
Select #Total = Count(1)
,#RowId = 1
From #EN As en With (Nolock)
Select #Total2 = Count(1)
,#RowId2 = 1
From #TableNamesToCheck As et With (Nolock)
While (#RowId <= #Total)
Begin
Select #EmpName = en.employeename
From #EN As en With (Nolock)
Where en.RowId = #RowId
While (#RowId2 <= #Total2)
Begin
Select #TableName = et.dbName
From #TableNamesToCheck As et With (Nolock)
Where et.dbId = #RowId2
Select #Sql = ' If Exists ' +
' ( ' +
' Select 1 ' +
' From ' + #TableName + ' As t With (Nolock) ' +
' Where t.employeename = ''' + #EmpName + ''' ' +
' ) ' +
' Begin ' +
' Insert Into #EnTables(EmployeeName,dbName) ' +
' Select ''' + #EmpName + ''' ' +
' ,''' + #TableName + ''' ' +
' End '
----Print(#Sql)
Exec (#Sql)
Select #RowId2 = #RowId2 + 1
End
Select #RowId = #RowId + 1
,#RowId2 = 1
,#EmpName = ''
,#TableName = ''
End
Select *
From #EnTables As et With (Nolock)
Related
Can anybody help on a problem I am having. For the software i am using it won't accept temp tables unless the table is created and inserted into just like i tried with this.
Before i put in the create table and insert into just the table it works fine but when i try this it says the table already exists.
Can anybody see what i am doing wrong and can advise, it's the variables in my temp tables that is throwing me off.
declare #bt_id varchar(20) = '110';
declare #ms_id varchar(20) = '2';
declare #sqlstr varchar(max) = '';
if object_id('tempdb..#measure_raw') is not null
drop table #measure_raw
CREATE TABLE #measure_raw(
meas_id INT,
column_name VARCHAR (255),
vlu_txt VARCHAR (255),
batch_id INT,
row_num INT,
)
insert into #measure_raw
set #sqlstr = 'select det.meas_id,col.tbl_nm+''.''+col.logged_nm as column_name, det.vlu_txt, det.batch_id, '
+ 'case when (det.row_num is null) then 1 else det.row_num end as row_num '
+ 'into #measure_raw from detail_t det '
+ 'inner join column_t col on col.col_id=det.col_id inner join measure_t rul on rul.meas_id=det.meas_id '
+ 'where det.batch_id = ' + #bt_id + ' '
if #ms_id <> '0'
set #sqlstr = #sqlstr + 'and det.meas_id = ' + #ms_id + ' '
set #sqlstr = #sqlstr + 'order by '
+ 'det.batch_id, det.meas_id, det.row_num, col.tbl_nm, col.logged_nm'
exec(#sqlstr)
I have a timed sync that references a remote database. The sync uses "Select *...". There have been some changes to the local DB structure, and now the sync fails of course because the columns are different.
How can I compare the two tables?
To get the local columms, I can do:
SELECT * -- COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
FROM information_schema.columns
WHERE table_name = 'Items'
ORDER BY ordinal_position
And to get the remote columns I can do:
EXECUTE [WebServ].[WebDB].dbo.sp_executesql
N'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM
INFORMATION_SCHEMA.COLUMNS
WHERE table_name like ''ITEMS_Web'''
But how would I put them together so it just shows me which columns have been added on the local table? I guess I just don't know how to get the results from the Execute command into a useable form so I could do a JOIN or something... Forgive my n00bieness. This is MSSQL 2008
I have a stored procedure to modify archive tables for me automatically.
I have modified it for you, leave the #COMMIT_CHANGES=0 and it will print out the alters required to update the 2nd table to match the first.
Be sure you fix the database and owner in the SET statements to match your own database tables.
I have disabled the EXEC that could potentially alter your table in case you accidentally set #COMMIT_CHANGES to 1... un-comment it if you want the #COMMIT_CHANGES flag to actually execute alter codes. If nothing is returned the tables match.
Edit: I am storing the commands in a table for email to myself, but I removed the email code from this example.
This should give a good foundation for anything you need it to do.
DECLARE #TABLENAME VARCHAR(100), #TABLENAME2 VARCHAR(100), #COMMIT_CHANGES BIT, #SSERVERNAME VARCHAR(100)
SET #TABLENAME='database.dbo.ITEMS' --local
SET #TABLENAME2='database.dbo.ITEMS_WEB' --remote
SET #SSERVERNAME = 'WEBSERV' --remote server
SET #COMMIT_CHANGES=0 -- set to 1, and it WILL change your remote table
SET NOCOUNT ON
DECLARE #SQL VARCHAR(MAX)
DECLARE #DB1 SYSNAME, #OWNER1 SYSNAME, #TABLE1 SYSNAME
DECLARE #DB2 SYSNAME, #OWNER2 SYSNAME, #TABLE2 SYSNAME
DECLARE #RECIPIENTS VARCHAR(500), #ENABLEEMAIL BIT
IF #COMMIT_CHANGES = 0 PRINT 'TEST MODE ONLY, CHANGES WILL NOT BE MADE'
-- PARSE TABLE NAME INTO 3 PARTS
SELECT #TABLE1 = PARSENAME(#TABLENAME, 1)
SELECT #OWNER1 = PARSENAME(#TABLENAME, 2)
IF #OWNER1 IS NULL SELECT #OWNER1 = 'DBO'
SELECT #DB1 = PARSENAME(#TABLENAME, 3)
IF #DB1 IS NULL SELECT #DB1 = DB_NAME()
-- PARSE ARCHIVE TABLE NAME INTO 3 PARTS
SELECT #TABLE2 = PARSENAME(#TABLENAME2, 1)
SELECT #OWNER2 = PARSENAME(#TABLENAME2, 2)
IF #OWNER2 IS NULL SELECT #OWNER2 = 'DBO'
SELECT #DB2 = PARSENAME(#TABLENAME2, 3)
IF #DB2 IS NULL SELECT #DB2 = DB_NAME()
-- IF OUR TEMP TABLES EXIST, DROP THEM
IF EXISTS (SELECT * FROM TEMPDB.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '##T1_MAIN') DROP TABLE ##T1_MAIN
IF EXISTS (SELECT * FROM TEMPDB.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '##T2_ARCHIVE') DROP TABLE ##T2_ARCHIVE
-- GATHER SCHEMA INFO FOR LIVE TABLE
SET #SQL = 'SELECT TABLE_NAME,
COLUMN_NAME,
DATA_TYPE,
ISNULL(CHARACTER_MAXIMUM_LENGTH,0) AS CHARACTER_MAXIMUM_LENGTH,
ISNULL(NUMERIC_PRECISION,0) AS NUMERIC_PRECISION,
ISNULL(NUMERIC_SCALE,0) AS NUMERIC_SCALE,
IS_NULLABLE,
CAST(0 AS BIT) AS ADD_COLUMN,
CAST(0 AS BIT) AS ALTER_COLUMN
INTO ##T1_MAIN
FROM ' + #DB1 + '.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ''' + #TABLE1 + '''
AND TABLE_SCHEMA = ''' + #OWNER1 + ''' '
--PRINT #SQL
EXEC(#SQL)
-- CHECK IF TABLES EXIST, ELSE SKIP ALL WORK
IF NOT EXISTS (SELECT * FROM TEMPDB.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '##T1_MAIN')
BEGIN
PRINT #TABLENAME + ' DOES NOT EXIST, EXITING PROC'
GOTO SKIPWORK
END
-- GATHER SCHEMA INFO FOR ARCHIVE TABLE
SET #SQL = 'SELECT TABLE_NAME,
COLUMN_NAME,
DATA_TYPE,
ISNULL(CHARACTER_MAXIMUM_LENGTH,0) AS CHARACTER_MAXIMUM_LENGTH,
ISNULL(NUMERIC_PRECISION,0) AS NUMERIC_PRECISION,
ISNULL(NUMERIC_SCALE,0) AS NUMERIC_SCALE,
IS_NULLABLE,
CAST(0 AS BIT) AS DROP_COLUMN
INTO ##T2_ARCHIVE
FROM ['+#SSERVERNAME+'].' + #DB2 + '.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ''' + #TABLE2 + '''
AND TABLE_SCHEMA = ''' + #OWNER2 + ''' '
--PRINT #SQL
EXEC(#SQL)
-- CHECK IF TABLES EXIST, ELSE SKIP ALL WORK
IF NOT EXISTS (SELECT * FROM TEMPDB.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '##T2_ARCHIVE')
BEGIN
PRINT #TABLENAME2 + ' DOES NOT EXIST, EXITING PROC'
GOTO SKIPWORK
END
-- FLAG NEW COLUMNS
-- COLUMN IN T1 (LIVE) BUT NOT IN T2 (ARCHIVE)
UPDATE T1 SET ADD_COLUMN = 1
FROM ##T1_MAIN T1
LEFT OUTER JOIN ##T2_ARCHIVE T2
ON T1.COLUMN_NAME = T2.COLUMN_NAME
WHERE T2.COLUMN_NAME IS NULL
-- FLAG REMOVED COLUMNS
-- COLUMN IN T2 (ARCHIVE) BUT NOT IN T1 (LIVE)
-- ** NOT DOING ANYTHING WITH THIS **
UPDATE T2 SET DROP_COLUMN = 1
FROM ##T2_ARCHIVE T2
LEFT OUTER JOIN ##T1_MAIN T1
ON T2.COLUMN_NAME = T1.COLUMN_NAME
WHERE T1.COLUMN_NAME IS NULL
-- FLAG ALTERED COLUMNS
-- ONLY NEED WHERE LIVE DATA LENGTH IS > THAN ARCHIVE DATA LENGTH
-- WE WOULDN'T WANT TO SHRINK A COLUMN AND TRUNCATE A VALUE
UPDATE T1 SET ALTER_COLUMN = 1
FROM ##T1_MAIN T1
JOIN ##T2_ARCHIVE T2
ON T1.COLUMN_NAME = T2.COLUMN_NAME
AND (T1.DATA_TYPE <> T2.DATA_TYPE
OR T1.CHARACTER_MAXIMUM_LENGTH > T2.CHARACTER_MAXIMUM_LENGTH
OR T1.NUMERIC_PRECISION > T2.NUMERIC_PRECISION
OR T1.NUMERIC_SCALE > T2.NUMERIC_SCALE
OR (T1.IS_NULLABLE = 'YES' AND T2.IS_NULLABLE = 'NO'))
DECLARE #COLUMN_NAME VARCHAR(100),
#DATA_TYPE VARCHAR(100),
#CHARACTER_MAXIMUM_LENGTH INT,
#NUMERIC_PRECISION INT,
#NUMERIC_SCALE INT,
#IS_NULLABLE VARCHAR(3)
-- CREATE A TEMP TABLE TO HOLD OUR COMMANDS FOR EMAIL
IF EXISTS (SELECT * FROM TEMPDB.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '##COMMANDLIST') DROP TABLE ##COMMANDLIST
CREATE TABLE ##COMMANDLIST (sText VARCHAR(1000))
DECLARE ALTER_COLUMN CURSOR LOCAL
FOR
SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, IS_NULLABLE
FROM ##T1_MAIN
WHERE ALTER_COLUMN=1
OPEN ALTER_COLUMN
FETCH NEXT FROM ALTER_COLUMN INTO #COLUMN_NAME, #DATA_TYPE, #CHARACTER_MAXIMUM_LENGTH, #NUMERIC_PRECISION, #NUMERIC_SCALE, #IS_NULLABLE
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = 'ALTER TABLE ' + #DB2 + '.' + #OWNER2 + '.' + #TABLE2 + ' ALTER COLUMN ' + #COLUMN_NAME + ' ' + CASE
WHEN #DATA_TYPE IN ('NCHAR','NVARCHAR','CHAR','VARCHAR') THEN #DATA_TYPE + ' (' + CAST(#CHARACTER_MAXIMUM_LENGTH AS VARCHAR(15)) + ')'
WHEN #DATA_TYPE IN ('TINYINT','SMALLINT','INT','BIGINT','BIT','UNIQUEIDENTIFIER') THEN #DATA_TYPE
WHEN #DATA_TYPE IN ('DECIMAL','MONEY','FLOAT','NUMERIC') THEN #DATA_TYPE + ' (' + CAST(#NUMERIC_PRECISION AS VARCHAR(15)) + ',' + CAST(#NUMERIC_SCALE AS VARCHAR(15)) + ')'
END
+ ' ' +
CASE
WHEN #IS_NULLABLE = 'YES' THEN 'NULL'
ELSE 'NULL'
END
PRINT #SQL
IF #COMMIT_CHANGES = 1
BEGIN
IF(##SERVERNAME <> #sServerName) SET #SQL = 'EXEC(''' + REPLACE(#SQL,'''','''''') + ''') AT ' + QUOTENAME(#sServerName)
EXEC(#SQL)
END
IF #SQL IS NOT NULL INSERT INTO ##COMMANDLIST (sText) SELECT #SQL
FETCH NEXT FROM ALTER_COLUMN INTO #COLUMN_NAME, #DATA_TYPE, #CHARACTER_MAXIMUM_LENGTH, #NUMERIC_PRECISION, #NUMERIC_SCALE, #IS_NULLABLE
END
CLOSE ALTER_COLUMN
DEALLOCATE ALTER_COLUMN
DECLARE ADD_COLUMN CURSOR LOCAL
FOR
SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, IS_NULLABLE
FROM ##T1_MAIN
WHERE ADD_COLUMN=1
OPEN ADD_COLUMN
FETCH NEXT FROM ADD_COLUMN INTO #COLUMN_NAME, #DATA_TYPE, #CHARACTER_MAXIMUM_LENGTH, #NUMERIC_PRECISION, #NUMERIC_SCALE, #IS_NULLABLE
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = 'ALTER TABLE ' + #DB2 + '.' + #OWNER2 + '.' + #TABLE2 + ' ADD ' + #COLUMN_NAME + ' ' + CASE
WHEN #DATA_TYPE IN ('NCHAR','NVARCHAR','CHAR','VARCHAR') THEN #DATA_TYPE + ' (' + CAST(#CHARACTER_MAXIMUM_LENGTH AS VARCHAR(15)) + ')'
WHEN #DATA_TYPE IN ('TINYINT','SMALLINT','INT','BIGINT','BIT','UNIQUEIDENTIFIER') THEN #DATA_TYPE
WHEN #DATA_TYPE IN ('DECIMAL','MONEY','FLOAT','NUMERIC') THEN #DATA_TYPE + ' (' + CAST(#NUMERIC_PRECISION AS VARCHAR(15)) + ',' + CAST(#NUMERIC_SCALE AS VARCHAR(15)) + ')'
END
+ ' ' +
CASE
WHEN #IS_NULLABLE = 'YES' THEN 'NULL'
ELSE 'NOT NULL'
END
PRINT #SQL
IF #COMMIT_CHANGES = 1
BEGIN
IF(##SERVERNAME <> #sServerName) SET #SQL = 'EXEC(''' + REPLACE(#SQL,'''','''''') + ''') AT ' + QUOTENAME(#sServerName)
-- uncomment this EXEC to make the commit changes flag work...
--EXEC(#SQL)
END
IF #SQL IS NOT NULL INSERT INTO ##COMMANDLIST (sText) SELECT #SQL
FETCH NEXT FROM ADD_COLUMN INTO #COLUMN_NAME, #DATA_TYPE, #CHARACTER_MAXIMUM_LENGTH, #NUMERIC_PRECISION, #NUMERIC_SCALE, #IS_NULLABLE
END
CLOSE ADD_COLUMN
DEALLOCATE ADD_COLUMN
SKIPWORK:
I have a query that selects from multiple tables using a join. I want to execute this query from different databases via a loop.
I have accomplished that via (simplified query):
DECLARE #intCounter int
SET #intCounter = 1
DECLARE #tblBedrijven TABLE (ID int identity(1,1),
CompanyName varchar(20),
DatabaseTable varchar(100))
INSERT INTO #tblBedrijven VALUES ('001-CureCare', '<TABLE/ DATABASE1> AUS'),
('002-Cleaning', '[global_nav5_prod].[dbo].<TABLE/ DATABASE2>] AUS')
DECLARE #strCompany varchar(20)
DECLARE #strTable varchar(100)
WHILE (#intCounter <= (SELECT MAX(ID) FROM #tblBedrijven))
BEGIN
SET #strTable = (SELECT DatabaseTable FROM #tblBedrijven
WHERE ID = #intCounter)
SET #strCompany = (SELECT CompanyName FROM #tblBedrijven
WHERE ID = #intCounter)
EXEC('SELECT ''' + #strCompany + ''' as Company,
AUS.[User],
AUS.[E-mail]
FROM' + #strTable)
SET #intCounter = #intCounter + 1
END
My problem is that the result generates 2 separate tables (for every loop). I want to union the results but have no clue how.
Any suggestions?
Thanks in advance.
Can't you use something like the below code where you append all the sqls with union and finally execute the sql once only without executing in a loop. I am not an expert in SQL Server but I have written many other similar stored procedures using other RDBMS. So please bear any syntax errors.
DECLARE #intCounter int
DECLARE #maxId int
SET #intCounter = 1
DECLARE #tblBedrijven TABLE (ID int identity(1,1),
CompanyName varchar(20),
DatabaseTable varchar(100))
INSERT INTO #tblBedrijven VALUES ('001-CureCare', '<TABLE/ DATABASE1> AUS'),
('002-Cleaning', '[global_nav5_prod].[dbo].<TABLE/ DATABASE2>] AUS')
DECLARE #strCompany varchar(20)
DECLARE #strTable varchar(100)
DECLARE #strSql varchar(5000)
SET #maxId = (SELECT MAX(ID) FROM #tblBedrijven)
WHILE (#intCounter <= #maxId)
BEGIN
SET #strTable = (SELECT DatabaseTable FROM #tblBedrijven
WHERE ID = #intCounter)
SET #strCompany = (SELECT CompanyName FROM #tblBedrijven
WHERE ID = #intCounter)
SET #strSql = #strSql + ('SELECT ''' + #strCompany + ''' as Company,
AUS.[User],
AUS.[E-mail]
FROM' + #strTable)
IF #intCounter < #maxId THEN
BEGIN
SET #strSql = #strSql + ' UNION '
END
SET #intCounter = #intCounter + 1
END
EXEC(#strSql)
i would like to alter a stored procedure so i will not suplly the identity column name
INSERT INTO tablName ..... WHERE IDENTITY_Column = 10
can i tell sql server managment studio to just refer to the IDENTITY column so it will find
it by its type which is (at least in my tables a default) autoincremet PK ID type
You haven't really given enough code for us to see what you are trying to do but from the snippet in the question.
WHERE IDENTITY_Column = 10
You can just use
WHERE $IDENTITY = 10
for that (to filter against an identity column without specifying the name).
If you do actually need to lookup the column name then an easier way, avoiding deprecated views is
SELECT name
FROM sys.identity_columns
WHERE object_id = object_id('dbo.YourTable')
found this information by now .
that is the plain and simple version .
declare #tblName sysname = '______'--<== enter a table name
declare #NameOfIDColumn sysname =
(
SELECT Name
FROM syscolumns
WHERE COLUMNPROPERTY( id ,name, 'IsIdentity') = 1 and OBJECT_NAME(id)= #tblName )
select #NameOfIDColumn AS 'result'
you could add this as an option to display last row of a table soretd by its record#
declare #query VARCHAR(100) = 'Select Top 1 * FROM '+ #tblName +' Order BY ' + #IdentColumnName + ' desc' ;
EXEC (#query);
and to play around or even make it as a test page in a .net project
make this one as a stored proc that will outpout a message to a test page .
declare #tblName sysname = '______'--<== enter a table name
declare #IdentColumnName sysname =
(
SELECT Name
FROM syscolumns
WHERE COLUMNPROPERTY( id ,name, 'IsIdentity') = 1 and OBJECT_NAME(id)= #tblName )
declare #result VARCHAR (50) = #tblName + ' Identity Column is ' + #IdentColumnName;
select #result AS 'result'
and with a shorter version of "idntity column search", by Martin Smith
declare #tblName sysname = '______'--<== enter a table name
declare #IdentColumnName sysname =
(SELECT name FROM sys.identity_columns WHERE object_id = object_id(#TableName))
declare #result VARCHAR (50) = #tblName + ' Identity Column is ' + #IdentColumnName;
select #result AS 'result'
this is related to a table copy trick i was trying to pull via stored procedure.
USE [YourDataBaseName]
GO
/****** Object: StoredProcedure [dbo].[Utils_TableRowCopy] Script Date: 10/03/2012 18:26:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Utils_TableRowCopy](
#TableName VARCHAR(50) ,
#RowNumberToCopy INT
)
AS
BEGIN
declare #RowIdentity sysname =
(
SELECT name FROM sys.identity_columns WHERE object_id = object_id(#TableName)
)
DECLARE #columns VARCHAR(5000), #query VARCHAR(8000);
SET #query = '' ;
SELECT #columns =
CASE
WHEN #columns IS NULL THEN column_name
ELSE #columns + ',' + column_name
END
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (
TABLE_NAME = LTRIM(RTRIM(#TableName))
AND
column_name <> LTRIM(RTRIM(#RowIdentity))
);
SET #query = 'INSERT INTO ' + #TableName + ' (' + #columns + ') SELECT ' + #columns + ' FROM ' + #TableName + ' WHERE ' + #RowIdentity + ' = ' + CAST(#RowNumberToCopy AS VARCHAR);
--SELECT SCOPE_IDENTITY();
declare #query2 VARCHAR(100) = ' Select Top 1 * FROM '+ #TableName +' Order BY ' + #RowIdentity + ' desc' ;
EXEC (#query);
EXEC (#query2);
END
I want to get all the transactions applied on a specific table in SQL Server 2008.
I found the last time a table was updated using this script:
SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'DBName')
AND OBJECT_ID=OBJECT_ID('tableName')
I want to know all the transactions (Inserts, Updates, Deletes) for that table, and their datetime, and the query applied.
What is the best way to do this?
The only way to do this in a reasonable amount of time is to use a third party tool(as Martin said in first comment) such as ApexSQL Log that can read transaction log and get the information you need.
Note that in order for this to work your database has to be in a full recovery mode because that’s when SQL Server logs full transaction details that can be reconstructed later.
Another option is to investigate how to use undocumented fn_dblog function but this will take you a lot more time and you won’t be able to read detached logs or transaction log backups.
creating a trigger which will create a new table Emp_audit and add new tuples to it whenever any change is made to table employee
create trigger my_trigger on Employees
AFTER INSERT, UPDATE, DELETE
AS
DECLARE #What varchar(30);
DECLARE #Who varchar(30);
DECLARE #for int;
DECLARE #At time;
DECLARE #COUNTI int;
DECLARE #COUNTD int;
select #COUNTI = COUNT(*) from inserted;
select #COUNTD = COUNT(*) from deleted;
set #Who = SYSTEM_USER;
set #At = CURRENT_TIMESTAMP;
if( #COUNTD = 0 and #COUNTI = 1)
begin
set #What = 'insert';
select #for = EmployeeID from inserted i;
end
else
begin
if( #COUNTD = 1 and #COUNTI = 0)
begin
set #What = 'delete';
select #for = EmployeeID from deleted i;
end
else
begin
set #What = 'update';
select #for = EmployeeID from inserted i;
end
end
INSERT INTO EMP_Audit Values (#What, #Who, #for, #At);
You would be much better off setting up auditing for this need rather than trying to extract this information retrospectively from the transaction log.
If you are on Enterprise Edition you could use the built in SQL Server Audit functionality, otherwise it should be relative straight forward to log the desired information via triggers.
You could create your own transaction logs
Step 1: Create your own table for transaction logs
CREATE TABLE [dbo].[TransactionLogs](
[TransactionLogID] [bigint] IDENTITY(1,1) NOT NULL,
[Query] [nvarchar](max) NOT NULL,
[DateCreated] [datetime] NOT NULL,
CONSTRAINT [PK_TransactionLogs] PRIMARY KEY CLUSTERED
(
[TransactionLogID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Step 2: Create stored procedure that create logs. (Note: Replace YourTablePKColumn with your table primary key column.)
create procedure [dbo].[sp_CreateQueryLogs]
(
#Query nvarchar(max) = null output,
#TableName nvarchar(100),
#YourTablePKColumn nvarchar(30),
#QueryTypeID tinyint --0 insert, 1 update, 2 delete
)
as
begin
declare #object_id bigint, #column_name nvarchar(100), #collation_name nvarchar(50), #column_name_id nvarchar(100) = null, #column_names nvarchar(max) = '', #column_values nvarchar(max) = '', #column_names_create nvarchar(max) = '', #values nvarchar(max) = '', #user_type_id int, #max_length nvarchar(10), #type_name nvarchar(50), #CreateTempTable nvarchar(max) = '', #is_nullable bit, #value nvarchar(max) = ''
create table #tmpValues(ColumnValues nvarchar(max))
insert into #tmpValues(ColumnValues)
exec('select CAST ( ( select * from ' + #TableName + ' where YourTablePKColumn = ' + #YourTablePKColumn + '
FOR XML PATH(''tr''), TYPE
) AS NVARCHAR(MAX) )')
select #values = ColumnValues from #tmpValues
if #QueryTypeID = 0 --insert
set #Query = 'insert into ' + #TableName + '('
else if #QueryTypeID = 1 --update
set #Query = 'update ' + #TableName + ' set '
else if #QueryTypeID = 2 --dalete
set #Query = 'delete ' + #TableName + ' '
select #object_id = object_id from sys.tables where name = #TableName
if not cursor_status('local','columnCursor') <= -1
begin
close columnCursor;
deallocate columnCursor;
end
declare columnCursor cursor local for
select name, user_type_id, convert(nvarchar(10), max_length), is_nullable from sys.columns where object_id = #object_id order by column_id ;
open columnCursor;
fetch next from columnCursor
into #column_name, #user_type_id, #max_length, #is_nullable;
while ##FETCH_STATUS = 0
begin
select #type_name = name, #collation_name = collation_name from sys.types where user_type_id = #user_type_id
if #column_name_id is null
set #column_name_id = #column_name
else
begin
set #column_names += #column_name + ', '
declare #value_keys_start nvarchar(max) = '<' + #column_name + '>', #value_keys_end nvarchar(max) = '</' + #column_name + '>'
if charindex(#value_keys_start,#values,1) = 0
begin
if #QueryTypeID = 0 --insert
set #column_values += 'null,'
else if #QueryTypeID = 1 --update
set #column_values += #column_name + ' = null,'
end
else
begin
if #QueryTypeID = 0 --insert
if #collation_name is null and not (#type_name like '%date%' or #type_name like '%time%')
set #column_values += substring(#values, charindex(#value_keys_start,#values,1) + len(#value_keys_start), charindex(#value_keys_end,#values,1) - (charindex(#value_keys_start,#values,1) + len(#value_keys_start))) + ','
else if #type_name like '%date%' or #type_name like '%time%'
set #column_values += '''' + replace(substring(#values, charindex(#value_keys_start,#values,1) + len(#value_keys_start), charindex(#value_keys_end,#values,1) - (charindex(#value_keys_start,#values,1) + len(#value_keys_start))),'T',' ') + ''','
else
set #column_values += '''' + replace(substring(#values, charindex(#value_keys_start,#values,1) + len(#value_keys_start), charindex(#value_keys_end,#values,1) - (charindex(#value_keys_start,#values,1) + len(#value_keys_start))),'''','''''') + ''','
else if #QueryTypeID = 1 --update
if #collation_name is null and not (#type_name like '%date%' or #type_name like '%time%')
set #column_values += #column_name + '=' + substring(#values, charindex(#value_keys_start,#values,1) + len(#value_keys_start), charindex(#value_keys_end,#values,1) - (charindex(#value_keys_start,#values,1) + len(#value_keys_start))) + ','
else if #type_name like '%date%' or #type_name like '%time%'
set #column_values += #column_name + '=' + '''' + replace(substring(#values, charindex(#value_keys_start,#values,1) + len(#value_keys_start), charindex(#value_keys_end,#values,1) - (charindex(#value_keys_start,#values,1) + len(#value_keys_start))),'T',' ') + ''','
else
set #column_values += #column_name + '=' + '''' + replace(substring(#values, charindex(#value_keys_start,#values,1) + len(#value_keys_start), charindex(#value_keys_end,#values,1) - (charindex(#value_keys_start,#values,1) + len(#value_keys_start))),'''','''''') + ''','
end
end
fetch next from columnCursor
into #column_name, #user_type_id, #max_length, #is_nullable;
end
if not cursor_status('local','columnCursor') <= -1
begin
close columnCursor;
deallocate columnCursor;
end
if #QueryTypeID = 0 --insert
set #Query += substring(#column_names,1,len(#column_names) - 1) + ')
values (' + substring(#column_values,1,len(#column_values) - 1) + ')'
else if #QueryTypeID = 1 --update or delete
set #Query += substring(#column_values,1,len(#column_values) - 1) + ' where YourTablePKColumn = ' + #YourTablePKColumn
else
set #Query += ' where YourTablePKColumn = ' + #YourTablePKColumn
end
Step 3: Created trigger to table you want to have transaction logs
CREATE TRIGGER trg_MyTrigger ON YouTableName
AFTER INSERT, DELETE, UPDATE
AS
BEGIN
SET NOCOUNT ON;
declare #TableName nvarchar(100) = 'YouTableName', #Query nvarchar(max), #QueryTypeID tinyint, #YourTablePKColumn nvarchar(30)
if exists(select * from deleted) and exists(select * from inserted)
begin
set #QueryTypeID = 1
if not cursor_status('local','updatedCursor') <= -1
begin
close updatedCursor;
deallocate updatedCursor;
end
declare updatedCursor cursor local for
select cast(YourTablePKColumn as nvarchar(30)) from inserted;
open updatedCursor;
fetch next from updatedCursor
into #YourTablePKColumn;
while ##FETCH_STATUS = 0
begin
exec dbo.sp_CreateQueryLogs #Query = #Query output, #TableName = #TableName, #YourTablePKColumn = #YourTablePKColumn, #QueryTypeID = #QueryTypeID
insert into TransactionLogs
(Query, DateCreated)
values (#Query,getdate())
fetch next from updatedCursor
into #YourTablePKColumn;
end
if not cursor_status('local','updatedCursor') <= -1
begin
close updatedCursor;
deallocate updatedCursor;
end
end
else if exists(select * from deleted) and not exists(select * from inserted)
begin
set #QueryTypeID = 2
if not cursor_status('local','deletedCursor') <= -1
begin
close deletedCursor;
deallocate deletedCursor;
end
declare deletedCursor cursor local for
select cast(YourTablePKColumn as nvarchar(30)) from deleted;
open deletedCursor;
fetch next from deletedCursor
into #YourTablePKColumn;
while ##FETCH_STATUS = 0
begin
exec dbo.sp_CreateQueryLogs #Query = #Query output, #TableName = #TableName, #YourTablePKColumn = #YourTablePKColumn, #QueryTypeID = #QueryTypeID
insert into TransactionLogs
(Query, DateCreated)
values (#Query,getdate())
fetch next from deletedCursor
into #YourTablePKColumn;
end
if not cursor_status('local','deletedCursor') <= -1
begin
close deletedCursor;
deallocate deletedCursor;
end
end
else
begin
set #QueryTypeID = 0
if not cursor_status('local','insertedCursor') <= -1
begin
close insertedCursor;
deallocate insertedCursor;
end
declare insertedCursor cursor local for
select cast(YourTablePKColumn as nvarchar(30)) from inserted;
open insertedCursor;
fetch next from insertedCursor
into #YourTablePKColumn;
while ##FETCH_STATUS = 0
begin
exec dbo.sp_CreateQueryLogs #Query = #Query output, #TableName = #TableName, #YourTablePKColumn = #YourTablePKColumn, #QueryTypeID = #QueryTypeID
insert into TransactionLogs
(Query, DateCreated)
values (#Query,getdate())
fetch next from insertedCursor
into #YourTablePKColumn;
end
if not cursor_status('local','insertedCursor') <= -1
begin
close insertedCursor;
deallocate insertedCursor;
end
end
END
GO