2016-02-18 34 views
2

使用SQL數據庫時,我想將表(workflowoutputcadas)中的一列(nonexcludedsites )更新爲特定行(40-50)的特定值。我所做的是這樣的:在SQL中,我想將特定行更新爲新值

update workflowoutputcadas 
set nonexcludedsites = 1 
FROM 
    (SELECT ROW_NUMBER() 
     OVER (ORDER BY nonexcludedsites) AS Row, 
     nonexcludedsites 
    FROM workflowoutputcadas) AS w 
WHERE Row between 40 and 50 

因此,對於這個例子,我想的是,我想行40-50被更新爲1,其餘是相同的。當我運行腳本,它結束了將整列更新爲1這不是我想要做的,你知道我在哪裏犯了錯誤嗎?

+0

是表中'row'列? – Jens

+0

好吧,你應該使用'UPDATE w'代替 – Lamak

+0

不,行不是我桌子上的一列。 – user2128119

回答

1

這樣的方式如何:

;WITH CteData 
AS 
(
    SELECT ROW_NUMBER() 
     OVER (ORDER BY nonexcludedsites) AS [Rows], 
     nonexcludedsites 
    FROM workflowoutputcadas 
) 
update CteData 
set nonexcludedsites = 1  
WHERE [Rows] between 40 and 50 

答2:

USE YourDatabase 
GO 
SELECT ROW_NUMBER() 
    OVER (ORDER BY nonexcludedsites) AS [Rows], 
    nonexcludedsites INTO #Temp 
FROM workflowoutputcadas 
GO 
UPDATE workflowoutputcadas 
set nonexcludedsites = 1 
FROM workflowoutputcadas INNER JOIN #Temp ON #Temp.nonexcludedsites = workflowoutputcadas.nonexcludedsites 
WHERE #Temp.[Rows] between 40 and 50 
GO 
DROP TABLE #Temp 

我假設nonexcludedsites是您可以使用關係

+0

當我閱讀,我得到這個錯誤: 錯誤:在或接近 「[」 LINE 5語法錯誤:OVER(ORDER BY nonexcludedsites)AS [行], ^ **** ******錯誤********** – user2128119

+0

奇怪,請再試一次我剛加了「;」在WITH語句 – jthalliens

+0

的開頭雅我試過它,沒有「;」但仍然給我一個錯誤。帶「;」的 它給了我: 錯誤:語法錯誤處於或接近「[」 LINE 5:OVER(ORDER BY nonexcludedsites)AS [Rows], ^ ********** ****** **** ERROR:在或接近 「[」 SQL狀態語法錯誤:42601 性格:93 而不: ERROR:語法錯誤處或附近 「[」 LINE 5:OVER(ORDER BY nonexcludedsites) AS [行], ^ ********** **********錯誤********** 錯誤:語法錯誤處於或接近「[」 SQL狀態:42601 字符:92 – user2128119

0

試試這個字段:

update workflowoutputcadas 
set nonexcludedsites = 1 
FROM 
workflowoutputcadas a --**** 
LEFT JOIN --**** 
    (SELECT ROW_NUMBER() 
     OVER (ORDER BY nonexcludedsites) AS Row, 
     nonexcludedsites 
    FROM workflowoutputcadas) AS w 
on a.nonexcludedsites = w.nonexcludedsites --**** 
WHERE Row between 40 and 50 

我添加commented-用星號標出我已添加到原始查詢中的行。

或者,您也可以使用兩個子查詢,但它開始變得混亂:

update workflowoutputcadas 
set nonexcludedsites = 1 
where nonexcludedsites in 
    (Select nonexcludedsites from 
     (SELECT ROW_NUMBER() 
     OVER (ORDER BY nonexcludedsites) AS Row, 
     nonexcludedsites 
    FROM workflowoutputcadas) AS w 
WHERE Row between 40 and 50)