SQL Server 2005 Query
EOY- End Of Year.. Happy New Year Everyone !!!
Well I had to update a Column End_Date to a particular value '12/31/2010' since it is the EOY. Instead of viewing each table and editing all the columns, I thought of writing a SQL Query to update all the End_Date to '12/31/2010' in all the tables.
SysObjects - It has the list of all tables present in the database.
SysColumns Table- It has the list of all the columns in all the tables in the database.
SysObjects and SysColumns are linked by "id" .
So here is the query to display all the table names based on the column end_dt.
SELECT SYSOBJECTS.NAME FROM SYSCOLUMNS
INNER JOIN SYSOBJECTS ON
SYSCOLUMNS.ID = SYSOBJECTS.ID
WHERE SYSCOLUMNS.NAME='END_DT';
Then I had to loop through each table using cursors and use the update statement to change the end_dt values.
Full Query :
SET QUOTED_IDENTIFIER ON
DECLARE @TableName varchar(100)
DECLARE @SQL VARCHAR(100)
DECLARE @getTableName CURSOR
SET @getTableName= CURSOR FOR
SELECT SYSOBJECTS.NAME FROM SYSCOLUMNS
INNER JOIN SYSOBJECTS ON
SYSCOLUMNS.ID = SYSOBJECTS.ID
WHERE SYSCOLUMNS.NAME='END_DT';
OPEN @getTableName
FETCH NEXT
FROM @getTableName INTO @TableName
while @@fetch_status = 0
begin
SET @SQL='update ' + @TableName + ' set end_dt=''12/31/2099'' where end_dt is null'
EXECUTE(@SQL)
fetch next
from @getTableName into @TableName
END
close @getTableName
deallocate @getTableName
Well I had to update a Column End_Date to a particular value '12/31/2010' since it is the EOY. Instead of viewing each table and editing all the columns, I thought of writing a SQL Query to update all the End_Date to '12/31/2010' in all the tables.
SysObjects - It has the list of all tables present in the database.
SysColumns Table- It has the list of all the columns in all the tables in the database.
SysObjects and SysColumns are linked by "id" .
So here is the query to display all the table names based on the column end_dt.
SELECT SYSOBJECTS.NAME FROM SYSCOLUMNS
INNER JOIN SYSOBJECTS ON
SYSCOLUMNS.ID = SYSOBJECTS.ID
WHERE SYSCOLUMNS.NAME='END_DT';
Then I had to loop through each table using cursors and use the update statement to change the end_dt values.
Full Query :
SET QUOTED_IDENTIFIER ON
DECLARE @TableName varchar(100)
DECLARE @SQL VARCHAR(100)
DECLARE @getTableName CURSOR
SET @getTableName= CURSOR FOR
SELECT SYSOBJECTS.NAME FROM SYSCOLUMNS
INNER JOIN SYSOBJECTS ON
SYSCOLUMNS.ID = SYSOBJECTS.ID
WHERE SYSCOLUMNS.NAME='END_DT';
OPEN @getTableName
FETCH NEXT
FROM @getTableName INTO @TableName
while @@fetch_status = 0
begin
SET @SQL='update ' + @TableName + ' set end_dt=''12/31/2099'' where end_dt is null'
EXECUTE(@SQL)
fetch next
from @getTableName into @TableName
END
close @getTableName
deallocate @getTableName
Comments
Post a Comment