如何自动化给定的SQL查询

时间:2011-04-25 20:47:48

标签: sql-server

我有一个更新查询,如下所示。有人可以告诉我如何自动化这个,请

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

对于第二部分,您可以轻松编写一个循环来循环遍历从2007年开始的所有年份到当前年份,这将自动化该部分。

你可能不想在第二步中自动执行第一步,因为这只是问问题,因为他们做了两件完全不同的事情。

答案 2 :(得分: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))