update record attributes in multiple tables
I need to update select o开发者_运维知识库ccurrences in different tables of the [ISD_ID] attribute, how might I accomplish this?
I can grab the set of tables that possess the records I'm looking for with this statement:
SELECT c1.TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS c1
INNER JOIN information_schema.COLUMNS c2
ON c1.TABLE_NAME = c2.TABLE_NAME
WHERE c1.COLUMN_NAME LIKE '%isd%id%' and c2.column_name LIKE '%schooldistrict%id%'
So now I have a set of table names that I'd like to iterate through, updating records as necessary.
Per a suggestion in another post, I've read up on Dynamic SQL. So I could do something like EXECUTE IMMEDIATE: ('update' + @tablename + ' set ISD_ID=37 where SchoolDistrictID=46')
.
My question, then, is: how can I iterate through my table names and substitute them into the above statement as the @tablename
variable, so that I can update the values in each table?
I also have the ability to use .NET and SSIS if need be.
Thanks in advance; I'm not so proficient with SQL and appreciate the opportunity to learn.
A weird way You can use an undocumented stored procedure (please don't tell Remus Rusanu I said that), to do something like this. You'd use the @where condition to specify that the table has to contain a given column.
A more conventional way would be to
- select the results of the query into a temp table or a table variable
- iterate over the temp table/table variable, using a while loop, grabbing the name of the table and substituting into the @tablename variable
- Execute your query above. Warning, you'd probably want to create variable called something like @myDynamicSQL, set the statement text to it, and then call EXEC IMMEDIATE on it.
Honestly, by the time you are done with "weird way", you'd be better off doing it the conventional way, but I'm just trying to be thorough.
If you want to use SSIS for this you can take the result from your first query into a RecordSet destination.
You can then make a foreach loop on the variable that keeps the recordset - and then for example make a SQL Task with an expression that does your "UPDATE " + (DT_STR,255,1252)@[User::tblname] + " SET ....."
as sqlStatementSource.
精彩评论