ADVANCED VERSION WITH GENERATING THE RIGHT DELETE STATEMENTS
BEGIN
-- The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__". The conflict occurred in database "", table "", column ''.
-- THIS SCRIPT DOESNT EXECUTE DELETE STATEMENTS IT ONLY GENERATES THE SQL STATEMENTS
declare @Subtable as nvarchar(100), @roottable as nvarchar(100), @idColumn as nvarchar(100)
set @Subtable=''
set @Roottable=''
set @idColumn=''
declare @SQLStatement as nvarchar(MAX) , @SQLStatement1 as nvarchar(MAX) ,@SQLStatement2 as nvarchar(MAX) ,@SQLStatement3 as nvarchar(MAX) ,
@orderstat as nvarchar(MAX) , @wherestat as nvarchar(MAX)
SET @orderstat = ' ORDER BY ' + @idColumn
SET @SQLStatement = 'SELECT TOP 1 @ItemId = ' + @idColumn + ' FROM ' + @Subtable + ' as st ' + ' where not exists(select * from ' + @Roottable + ' as rt where st.' + @idColumn + '=rt.' + @idColumn + ')and ' + @idColumn + ' is not null'
SET @SQLStatement2 = 'SELECT TOP 1 ' + @idColumn + ' FROM ' + @Subtable + ' as st ' + ' where not exists(select * from ' + @Roottable + ' as rt where st.' + @idColumn + '=rt.' + @idColumn + ')and ' + @idColumn + ' is not null'
SET @SQLStatement3 = ' '' DELETE FROM ' + @Subtable + ' WHERE ' + @idColumn + '= '' + CONVERT(NVARCHAR(10),@ItemId) '
SET @SQLStatement1 = '
BEGIN
Declare @ItemId bigint
' + @SQLStatement + @orderstat + '
PRINT ' + @SQLStatement3 + '
WHILE @ItemId is not null
BEGIN
if exists (' + @SQLStatement2 + ' AND ' + @idColumn + '>@ItemId '+ @orderstat + ')
begin
' + @SQLStatement + ' and ' + @idColumn + '>@ItemId '+ @orderstat + '
PRINT ' + @SQLStatement3 + '
end
else
begin
set @ItemId=null
end
END
END'
exec sp_executesql @SQLStatement1
END
Geen opmerkingen:
Een reactie posten