通过从表中选择来创建DELETE查询

时间:2019-04-10 07:18:28

标签: sql-server

在我的项目(自动化测试)中,我向数据库中添加了很多数据,应该在运行所有方案后将其删除,但是在极少数情况下,当执行崩溃时,有时会留下未删除的记录。

出于这个原因,我决定另外将所有创建的记录存储到要存储的其他表中:

  1. 插入新记录的表的新
  2. 用于删除语句中where子句的字段名称
  3. 表中记录的ID

enter image description here

现在,我试图从上表中选择所有记录,并使用它来创建删除查询。

是否可以在单个查询中完成?

SELECT * FROM AutomationTestingData AS atd 

DELETE FROM atd.TableName WHERE atd.DeleteByField = atd.RecordId

任何帮助,感激之情。

3 个答案:

答案 0 :(得分:2)

嗨,如果我了解您的所有尝试,我认为这可以回答:

SET NOCOUNT ON;  

DECLARE  @query varchar(4000);  

PRINT '-------- Deleting rows --------';  

DECLARE deleting_cursor CURSOR FOR   
SELECT 'DELETE FROM ' + atd.TableName + ' WHERE ' + atd.DeleteByField + ' = ' + atd.RecordId + ';'
FROM AutomationTestingData AS atd 

OPEN deleting_cursor  

FETCH NEXT FROM deleting_cursor   
INTO @query  

WHILE @@FETCH_STATUS = 0  
BEGIN  

    EXEC(@Query)

    FETCH NEXT FROM deleting_cursor   
    INTO @query  
END   
CLOSE deleting_cursor;  
DEALLOCATE deleting_cursor;  

CURSOR SQL:https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql?view=sql-server-2017

执行动态SQL Server:https://docs.microsoft.com/en-us/sql/t-sql/language-elements/execute-transact-sql?view=sql-server-2017

答案 1 :(得分:2)

您可以像这样为每个表编写一条删除语句

delete from Company 
where  id in ( select RecordId from adt where adt.TableName = 'Company')

delete from PickListValues 
where  id in ( select RecordId from adt where adt.TableName = 'PickListValues')

被授予,它不是真正的动态,但是它比动态sql和游标还快

修改
如果您需要全自动,请使用dynamic sql,如@pascalsanchez建议的那样

我会像这样改变光标

declare deleting_cursor cursor for
select 'delete from ' + adt.TableName + 
       'where ' + adt.DeleteByField + ' in (select RecordID from adt where adt.TableName = ''' + adt.TableName + ''')
from   AutomationTestingData AS atd 
group by adt.TableName, adt.DeleteByField

答案 2 :(得分:0)

您可以使用以下语法:

delete T1
from Table1 T1 join Table2.T2 on T1.SomeField=T2.SomeField
where Some Condition