2016-08-19 78 views
1

我的任務是自動執行一些操作(刪除數據庫中的舊行),現在這些操作都是手動完成的。 目前我有兩個MSSQL腳本。 第一個提取ID,我必須處理,以及爲每個ID刪除多個行。它看起來像這樣:如何合併兩個SQL腳本?

​​

所以,當我收到的所有ID我有,我啓動第二個腳本,每ID(手動更改腳本中的數量和relunching它的每一行工作從第一個選擇):

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 

那麼,如何將這些腳本合併爲一個腳本來啓動整個腳本?

回答

1

你幾乎完成CURSOR聲明。在沒有討論解決方案本身的情況下,帶有「合併」查詢的代碼將如下所示:

/* your declared variables and cursor variable */ 
DECLARE 
    @crBatches CURSOR, 
    @counter INT, 
    @fdel INT, 
    @csize INT = 500, 
    @batchId INT 

/* your first query declared as cursor/source for looping through batch_ids */ 
SET @crBatches = CURSOR FAST_FORWARD FOR 
SELECT e.batchId, 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] 

OPEN @crBatches 

FETCH NEXT FROM @crBatches 
INTO @batchId, @fdel 

/* loop on batch_ids obtained from cursor */ 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    SET @counter = 0 

    /* internal loop - your second query */ 
    While (@counter < @fdel) 
    BEGIN 
     SET @counter = @counter + @csize 

     BEGIN TRAN 
     DELETE top(@csize) from dbo.Logs where batchId = @batchId 
     COMMIT TRAN 
    END 

    FETCH NEXT FROM @crBatches 
    INTO @batchId, @fdel 
END 

CLOSE @crBatches 
DEALLOCATE @crBatches 
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]));