试试这个,它会生成你的语句。请原谅我写得很快的格式:
DECLARE @i INT, @SQL NVARCHAR(2000), @TABLENAME NVARCHAR(100)
SET @i = 1
SET @TABLENAME = 'informer_alert'
SET @SQL = ''
DECLARE @col VARCHAR(50), @basecol VARCHAR(50), @tname VARCHAR(50)
DECLARE @TABLE TABLE ([table] VARCHAR(50), col VARCHAR(50), basecol VARCHAR(50))
INSERT INTO @TABLE
SELECT t.name, sc.name, sc2.name
FROM sys.foreign_key_columns fk
INNER JOIN sys.tables t ON fk.parent_object_id = t.OBJECT_ID
INNER JOIN syscolumns sc ON fk.parent_column_id = sc.colorder
AND sc.id = fk.parent_object_id
INNER JOIN syscolumns sc2 ON fk.referenced_object_id = sc2.id
AND fk.constraint_column_id = sc2.colorder
WHERE fk.referenced_object_id = (SELECT OBJECT_ID
FROM sys.tables
WHERE name = @TABLENAME)
WHILE (@i <= (SELECT COUNT(*) FROM @TABLE))
BEGIN
SELECT @tname = [table], @col = col, @basecol = basecol
FROM (SELECT ROW_NUMBER() OVER(ORDER BY col) [N],
[table], col, basecol
FROM @TABLE) A
WHERE A.N = @i
SET @SQL = @SQL + ' DELETE FROM ' + @TABLENAME + ' WHERE ' + @basecol + ' NOT IN (SELECT ' + @col+ ' FROM ' + @tname + ')'
SET @i = @i + 1
END
SELECT @SQL