I have several customer databases that contain tables and columns of the same name, and those tables contain misspellings in a few fields. The IDs are different in all tables, however. I want to easily update the string text for those columns across all database. I know the names of the main 5 databases, but there are more than 50. I accomplished this for one database, as that was what was originally requested, but I was told to do it dynamically.
Example of one fix that worked for ONE database:
UPDATE dbo.QuestionnaireQuestionLookup
SET QuestionText = 'Person with a serious mental illness'
WHERE QuestionnaireQuestionId = 18 AND QuestionnaireFormTypeId = 11;
The IDs vary. I am trying to get this to work within all databases, even if the name is not known. I know that the Column and Table names are always the same, but I need to update it across all DBs, regardless of the IDs in each table. I do not think omitting the IDs will solve this issue. Any tips would be much appreciated. I could not find any questions/answers here that applied to my exact scenario.
2条答案
按热度按时间pieyvz9o1#
You can use sp_msforeachdb to loop databases:
The procedure runs the provided sql string in all your databases. The database being run is passed in the "?", so one can do things like USE [?] to change to that database.
Note that procedure has some quirks, but works mostly ok, you can search around for alternatives as well.
Inside the string, you check so your table actually exists by doing OBJECT_ID('tablename'). Then, the real problem becomes on how to update your data. I have no idea how you can achieve that if ids are all different, but you can probably use some LIKEs or something like that to match the text.
One complication is that all quotes (') inside the string must be quoted again, this makes query writing a bit cumbersome
juud5qan2#
First you have to do documentation work.
i )Prepare list of all
| ColumnName |TableName | DatabaseName | Server IP|
where spelling correction is requireBy doing this automatic idea will come. OR you can then update question accordingly here along with sample data.
So far whatever I understood, This is not tested and also ignore syntax error
Customized suiting your requirement. For now it work only in one database.
So do the cursor & dynamic query work and let us know