我的任务是自动执行某些操作(从数据库中删除旧行),现在这些操作都是手动完成的。 目前我有两个MSSQL脚本。 第一个获取ID,我必须使用,以及为每个ID删除许多行。它看起来像那样:
SELECT e.batchId, b.Name, count (*) "Count"
FROM dbo.[Logs] e
join [dbo.[Batch] b on b.Id = e.batchId
Group by e.batchId, b.Name
Having count(*) > 500
order by [Count]
因此,在我收到我必须使用的所有ID之后,我为每个ID启动第二个脚本(手动更改脚本中的数字,并从第一个选择的每一行重新启动它):
Declare @counter INT
Declare @fdel INT
Declare @csize INT
Declare @batchId INT
select @batchId=666777 --HERE IS AN ID I CHANGE MANUALLY AND RELAUNCH THE SECOND ONE SCRIPT FOR IT
select @csize=500
select @counter = 0
select @fdel=count(*) from dbo.Logs where batchId = @batchId
While (@counter < @fdel)
BEGIN
select @counter = @counter + @csize
BEGIN TRAN
DELETE top(@csize) from dbo.Logs where batchId = @batchId
COMMIT TRAN
END
那么,如何将这些脚本合二为一,只启动整个脚本一次?
答案 0 :(得分:1)
您可以使用子选择和
中的位置delete from dbo.Logs
where id in ( select id_to_del from
( SELECT e.batchId as id_to_del, b.Name, count (*) "Count"
FROM dbo.[Logs] e
join [dbo.[Batch] b on b.Id = e.batchId
Group by e.batchId, b.Name
Having count(*) > 500
order by [Count]) );
答案 1 :(得分:1)
您几乎完成了CURSOR声明。如果不讨论解决方案本身,那么“合并”查询的代码将如下所示:
//Some methods here which don't use the globalVariable
int globalVariable = 3
//Some methods here which use the globalVariable