今天, 我想从sql server中的几个表中删除所有测试记录。 这是我要实现的目标。
Select ID from sourceTable where acctType='S' and acctroot<>0
假设此查询返回5行。
| ID|
---
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
现在这些是我需要清理的表
delete from tmpA where ID=1
delete from tmpB where acctID=1
delete from tmpC where userID = 1
delete from tmpD where sID=1
.
.
.
delete from tmpA where ID=2
delete from tmpB where acctID=2
delete from tmpC where userID =2
delete from tmpD where sID=2
我可以遍历源表并提取ID,然后从表中删除吗?我知道我可以使用联接,但是我想使用While循环来实现。.
答案 0 :(得分:2)
就这么简单
... WHERE ID IN (Select ID from sourceTable where acctType='S' and acctroot<>0)
赞:
delete from tmpA where ID IN (Select ID from sourceTable where acctType='S' and acctroot<>0)
delete from tmpB where acctID IN (Select ID from sourceTable where acctType='S' and acctroot<>0)
delete from tmpC where userID IN (Select ID from sourceTable where acctType='S' and acctroot<>0)
delete from tmpD where sID IN (Select ID from sourceTable where acctType='S' and acctroot<>0)
答案 1 :(得分:1)
您不需要WHILE
循环,可以像使用WHERE EXISTS
一样进行操作。
DELETE A
FROM tmpa a
WHERE EXISTS (SELECT 1
FROM sourcetable s
WHERE s.accttype = 'S'
AND s.acctroot <> 0
AND s.id = a.id)
您还需要对其他表执行相同的操作。
答案 2 :(得分:1)
您不需要while循环
delete from tmpA where ID IN (Select ID from sourceTable where acctType='S' and acctroot<>0)
答案 3 :(得分:0)
确保ID在源表中存在的另一种方法是使用INNER JOIN。
DELETE T
FROM tmpA T
INNER JOIN sourcetable S ON S.id = T.id AND S.accttype = 'S' AND S.acctroot <> 0
答案 4 :(得分:0)
尝试一下
Declare @Temp_Table Table (Id int identity(1,1),Table_Name varchar(30),Column_Name varchar(30))
insert into @Temp_Table
select 'tmpA','ID'
union all
select 'tmpB','acctID'
union all
select 'tmpC','userID'
union all
select 'tmpD','sID'
Declare @Counter int=1
,@Tot_Count int=0
,@Table_Name varchar(30)=''
,@Column_Name varchar(30)=''
select @Tot_Count=count(1)
from @Temp_Table
While @Tot_Count >= @Counter
Begin
Select @Table_Name=Table_Name
,@Column_Name=Column_Name
From @Temp_Table
Where Id=@Counter
Exec
(
'
Delete A
From '+@Table_Name+' A
inner join sourceTable B
on A.'+@Column_Name+'=B.ID
where B.acctType=''S''
and B.acctroot<>0
'
)
Set @Counter+=1
End