2011-04-25 4 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

* * 쿼리 및 그 희망을 분명히해야합니다. –

+0

'value'는 쿼리 수정 시마다 동일하거나 다를 것입니까? –

답변

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 
관련 문제