Skip to content
Advertisement

How to update several tables with a result query?

I am working with SQL Server 2017, and I need to clean up duplicate rows and update all rows in other tables that contain my field.

I’ve got one table which contains my customers

Then I have 7 tables that contains the userid column and 1 table with another name column

My other tables:

I want to clean the duplicates and keep only one record in the database.

First, I created a query that gives me only the duplicate rows and keeps only one record.

With this record, I’ll update table3, table4, table5, table6,

Then I created a query that gives me all the tables that contain my ‘Userid’ column.

This query will return: table3, table4, table5, table6

And finally I created my merge query

My merge result:

It works very well, but is there a way to automatize it ? Actually I’ve created 8 queries, but only the merge section change. Also, how can I remove duplicate rows in my dbo.users table, after all fields have been updated?

Thank you for your help.

Advertisement

Answer

I came back to answer to my own question. After some days i finally did it.

beforehand I’ve created a table which comes from my CTE query (singleUser)

I don’t know if it’s well coded because it’s the first time I’ve done this. For example I’ve seen on some forum they put the ; after FETCH / CLOSE / DEALLOCATE ; others not.

with semicolon

Microsoft without semicolon

so Who is right or wrong, dunno ?

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement