在SQL中,我想将特定行更新为新值

时间:2016-02-18 18:59:57

标签: sql-server

使用SQL数据库,我想更新一列(nonexcludedsites 在表(workflowoutputcadas)中为某些行(40-50)的特定值。我做的是这个:

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,这不是我想要做的。你知道我在哪里弄错了吗?

2 个答案:

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

我假设notxcludedsites是一个可用于关系的字段

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

我添加了已注释掉的星号,以标记我已添加到原始查询中的行。

或者,您可以使用两个子查询,但它开始变得混乱:

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)