2015-09-04 83 views
-6

我繼承了SQL Server的下面的代碼:SQL服務器循環和遊標

SET NOCOUNT ON 
DECLARE 
@PERSON_ID AS INT, 
@COMMS_DATE AS DATE, 
@PERSON_ID_HOLD AS INT, 
@COMMS_DATE_HOLD AS DATE, 
@CAMPAIGN_ID AS INT, 
@CAMPAIGN_ID_OLD AS INT, 
@SQL AS VARCHAR(200) 

SELECT @PERSON_ID_HOLD = 0 
SELECT @COMMS_DATE_HOLD = null 
SELECT @CAMPAIGN_ID = 0 
SELECT @CAMPAIGN_ID_OLD = 0 

DECLARE COMMS_CURSOR CURSOR FOR 
SELECT PERSONID, ReportDate FROM ##Motability_Comms_Combined order by PersonID, ReportDate 

OPEN COMMS_CURSOR 
FETCH NEXT FROM COMMS_CURSOR 
INTO @PERSON_ID, @COMMS_DATE 

WHILE @@FETCH_STATUS = 0 
BEGIN 
IF (@PERSON_ID = @PERSON_ID_HOLD) and (DATEDIFF(day,@COMMS_DATE_HOLD,@COMMS_DATE) > 90) 
BEGIN 
IF @CAMPAIGN_ID = 0 
begin 
SET @PERSON_ID_HOLD = @PERSON_ID 
SET @COMMS_DATE_HOLD = @COMMS_DATE 
end 
ELSE 
begin 
SET @CAMPAIGN_ID_OLD = @CAMPAIGN_ID 
SET @CAMPAIGN_ID = @CAMPAIGN_ID + 1 
END 
end 
ELSE 

IF (@PERSON_ID <> @PERSON_ID_HOLD)-- or (@COMMS_DATE <> @COMMS_DATE_HOLD) 
BEGIN 
SET @CAMPAIGN_ID = 1 
SET @CAMPAIGN_ID_OLD = @CAMPAIGN_ID 
END 

IF (@CAMPAIGN_ID > 1) 
BEGIN 
UPDATE ##Motability_Comms_Combined SET Derived_Campaign_ID = @CAMPAIGN_ID WHERE personid = @PERSON_ID AND REPORTDATE = @COMMS_DATE --WHERE CURRENT OF COMMS_CURSOR 
END 

SET @PERSON_ID_HOLD = @PERSON_ID 
SET @COMMS_DATE_HOLD = @COMMS_DATE 
FETCH NEXT FROM COMMS_CURSOR INTO @PERSON_ID, @COMMS_DATE 
END 

CLOSE COMMS_Cursor 
DEALLOCATE COMMS_Cursor 

UPDATE ##Motability_Comms_Combined SET Derived_Campaign_ID = 1 WHERE Derived_Campaign_ID is null 

SET NOCOUNT OFF 

請有誰能夠告訴我這種SQL的目的是如nocount,聲明,遊標,等等?有沒有另一種方式來做選擇呢?

感謝您提前提供任何幫助。

+1

你甚至嘗試使用谷歌或閱讀手冊? – lad2025

+0

也許嘗試並詢問一個更具體的問題 – jazza1000

+0

Thanks lad2025。你有沒有試過學英語? – nk10

回答

0
  • SET NOCOUNT ON將阻止返回消息說明有多少行被更新。在代碼中的某些情況下,這是必要的,因爲該消息被解釋爲附加的結果集。此消息還有一些額外開銷。
  • CURSORS用於以過程方式執行操作,而不是通常的基於集合的方式(例如,如果您需要循環執行一些數據,爲每行執行存儲過程)。他們非常耗費資源,而且通常會皺眉。看起來,這可以在沒有遊標的情況下被重寫。

  • 「## Motability_Comms_Combined是全局臨時表,所以也可以通過其他的代碼被稱爲(在不同的SQL連接)

+0

感謝您的解釋。在SQL Server Management Studio中,您是否知道是否有一種方法可以逐步執行循環的一步看到輸出? – nk10

+0

還是有一個標準的方法,而不是使用遊標? – nk10

+0

您可以右鍵單擊Management Studio中的存儲過程並選擇執行。您可以在存儲過程中放置​​斷點來停止並檢查變量等。 – jazza1000