我无法更新特定列为NULL且另一列为2的第一个可用行。
ID UserID Model
1 124 2
2 125 1
3 126 1
4 NULL 3
5 NULL 2
5 NULL 2
我可以使用UserID更新第一个可用行,ID为4,但是一旦我添加了一个额外的条件,例如`AND Model =' 2'查询返回0行受影响。
这是我制作并尝试使用的查询:
UPDATE Table SET UserID = '127'
WHERE UserID IS NULL AND Model = '2'
AND ID IN (SELECT top 1 ID FROM Table where UserID IS NULL) /*Update only 1 row
如果我删除AND Model = '2'
,它仍然会更新第一个可用行,但我正在使用一个非常大的表,并且如果模型也是2那么我想指定只更新它。
答案 0 :(得分:2)
WITH cte as (
SELECT *
, row_number() over (partition by [UserID] order by [ID]) as rn
FROM Table1
WHERE Model = 2
AND UserID IS NULL
)
UPDATE cte
SET [UserID] = 'Updated'
WHERE rn =1;
SELECT *
FROM Table1
<强>输出强>
答案 1 :(得分:2)
您可以使用窗口函数来确定结果集中的第一条记录,并仅更新第一条记录:
;With ToUpdate As
(
Select *,
Row_Number() Over (Partition By Model Order By Id) As RN
From Table
Where UserId Is Null
)
Update ToUpdate
Set UserId = 127
Where Model = 2
And RN = 1
答案 2 :(得分:1)
添加
更新时TOP(1)
进入您的标准
示例:
UPDATE Table SET UserID = '127'
WHERE UserID IS NULL AND Model = '2'
AND ID = (select top(1) id from category WHERE UserID IS NULL AND Model = '2')