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
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