The column is "CreatedDateTime" which is pretty self-explanatory. It tracks whatever time the record was commited. I need to update this value in over 100 tables and would rather have a cool SQL trick to do it in a couple lines rather than copy pasting 100 lines with the only difference being the table name.
Any help would be appreciated, having a hard time finding anything on updating columns across tables (which is weird and probably bad practice anyways, and I'm sorry for that).
Thanks!
EDIT: This post showed me how to get all the tables that have the column
I want to show all tables that have specified column name
if that's any help. It's a start for me anyways.
First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.
UPDATE syntax:UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID.
To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.
If that's a one time task, just run this query, copy & paste the result to query window and run it
Select 'UPDATE ' + TABLE_NAME + ' SET CreatedDateTime = ''<<New Value>>'' '
From INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'CreatedDateTime'
You can use the Information_Schema.Columns to build update scripts for you.
Declare @ColName as nVarchar(100), @NewValue as nVarchar(50)
Set @ColName = 'Modified' -- 'your col name'
Set @NewValue = '2013-11-04 15:22:31' -- your date time value
Select 'Update ' + TABLE_NAME + ' set ' + COLUMN_NAME + ' = ''' + @NewValue + '''' From INFORMATION_SCHEMA.COLUMNS Where column_name = 'modified'
You could try using a cursor : like this
declare cur cursor for Select Table_Name From INFORMATION_SCHEMA.COLUMNS Where column_name = 'CreatedDateTime'
declare @tablename nvarchar(max)
declare @sqlstring nvarchar(max)
open cur
fetch next from cur into @tablename
while @@fetch_status=0
begin
--print @tablename
set @sqlstring = 'update ' + @tablename + ' set CreatedDateTime = getdate()'
exec sp_executesql @sqlstring
fetch next from cur into @tablename
end
close cur
deallocate cur
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With