2011-04-25 19 views
0

我有一個更新查詢,如下所示。誰能告訴我如何自動執行此,請如何自動化給定的SQL查詢

1)I have to execute First part. 
2)Then comment line "AND s.ExtractYear = l.ExtractYear"... 
3)Uncomment "--and l.ExtractYear = 2011" and "--WHERE s.Prod IS NULL", then execute. 
4)Uncomment "--and l.ExtractYear = 2010" and "--WHERE s.Prod IS NULL", then execute. 
5)Uncomment "--and l.ExtractYear = 2009" and "--WHERE s.Prod IS NULL", then execute. 
6)Uncomment "--and l.ExtractYear = 2008" and "--WHERE s.Prod IS NULL", then execute. 
7)Uncomment "--and l.ExtractYear = 2007" and "--WHERE s.Prod IS NULL", then execute. 

--First part 
UPDATE s 
Set Col1 = value 
FROM table1 s 
INNER JOIN LkpTable l 
ON 
s.PId= l.PId 
AND s.ExtractYear = l.ExtractYear 


--Second part 
--and l.ExtractYear = 2011 
--and l.ExtractYear = 2010 
--and l.ExtractYear = 2009 
--and l.ExtractYear = 2008 
--and l.ExtractYear = 2007 
--WHERE s.Prod IS NULL 
+1

我不清楚你正在試圖與註釋和取消註釋等,到底該怎麼做,你能否告訴前三**完整* *查詢和應該明確希望。 – 2011-04-25 21:01:14

+0

對於查詢的每個修改,「值」是相同的還是不同的? – 2011-04-25 21:48:18

回答

0

對於第二部分,你可以很容易地通過編碼這些年的循環週期,以從2007年開始到今年這會自動執行部分。

您可能不希望第二步自動化第一步,因爲這只是要求問題,因爲他們正在做兩件完全不同的事情。

0

這是我最好的客人,沒有表結構和一些示例數據來測試。你正在測試這個查詢的地方,對吧? :)

UPDATE s 
    SET Col1 = value 
FROM 
    table1 s 
     INNER JOIN 
    LkpTable l 
     ON 
     s.PId= l.PId 
      AND 
     (s.ExtractYear = l.ExtractYear 
      OR 
     (l.ExtractYear IN (2007, 2008, 2009, 2010, 2011) 
      AND 
      s.Prod IS NULL)) 
1

試試這個:

-- Will use EXECUTE statement as 
-- 'Execute a character string' 
DECLARE @cmdUpdate VARCHAR(200) 
DECLARE @iYear INT 
DECLARE @cYear VARCHAR(5) 

SET @cmdUpdate = 'UPDATE s 
        Set Col1 = value 
        FROM table1 s 
        INNER JOIN LkpTable l 
        ON 
        s.PId= l.PId' 

SET @iYear = 2012 
WHILE @iYear >= 2007 
BEGIN 
    SET @cYear = CONVERT(VARCHAR(5), @iYear) 
    IF @iYear > 2011 
    -- Executing the first part (@iYear = 2012) 
    EXECUTE (@cmdUpdate + ' AND s.ExtractYear = l.ExtractYear') 
    ELSE 
    -- Executing all other parts consecutively 
    EXECUTE (@cmdUpdate + ' and l.ExtractYear = ' + @cYear + ' WHERE s.Prod IS NULL') 
    SET @iYear = @iYear - 1 
END