Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete all rows in all table that reference to user table with same where condition table

I want to delete all rows of all tables that reference the user table in SQL Server

User Table Name : security.User
User Table PK : UserId

My query for table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Delete From FKschema.FKTable where FKColumn not in (1,2)

How can I do this with one query for all tables?

>Solution :

You should use CURSOR and create string and execute it

DECLARE @tableName NVARCHAR(100), @schema NVARCHAR(50), @refcolumn NVARCHAR(50)
DECLARE @Query NVARCHAR(max)= ' DELETE from %s.%s where %s not in (1,2)'


DECLARE Cur CURSOR FOR
SELECT object_name(fk.parent_object_id) as Table_Name,SCHEMA_NAME(schema_id),(SELECT name FROM sys.columns c WHERE c.column_id=fk_cols.parent_column_id AND c.object_id=fk.parent_object_id) AS columnName 
FROM sys.foreign_keys fk
inner join sys.foreign_key_columns fk_cols
    on fk_cols.constraint_object_id = fk.object_id
WHERE fk.referenced_object_id = object_id('security.users','U');



OPEN Cur
FETCH NEXT FROM Cur INTO @tableName, @schema,@refcolumn
WHILE @@FETCH_STATUS=0
BEGIN
    DECLARE @text NVARCHAR(max)=FORMATMESSAGE(@Query, @schema,@tableName,@refcolumn) 
    EXECUTE(@text)
    FETCH NEXT FROM Cur INTO @tableName, @schema,@refcolumn
    PRINT @text
END

CLOSE Cur
DEALLOCATE Cur
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading