我如何随机更新我的2行,在SQL Server中有这个编码F01 = 1和F03 = 1

时间:2015-04-19 10:31:04

标签: sql sql-server sql-server-2008

如何在具有5行的表中具有此条件F01=1 And F02=1的其他4行中随机更新我的2行? 并且我想要在执行代码后更改的行数。

像这样

ID   F01   F02         ID    F01    F02
1    0     1           1     0      1
2    1     1           2     A      1
3    1     1      -->  3     1      1
4    1     1           4     1      1
5    1     1           5     A      1 
最后我在另一张桌子上有2号和5号。

这些数字只是例如。

我不能使用newid(),因为SQL表示你不能在子查询中使用order by。

这是我的代码不起作用

Update Chess.dbo.Sheet1$ 
set F01 = A 
Where ID in (select top 2 ID 
             from Chess.dbo.Sheet1$ 
             where (select ID from Chess.dbo.Sheet1$ order by NEWID())

3 个答案:

答案 0 :(得分:7)

;WITH CTE AS 
(
 SELECT TOP 30 *
 FROM TableName 
 WHERE F01 = 1 AND F02 = 1
 ORDER BY NEWID()
)
UPDATE CTE 
 SET ColumnName = 'NewValue'

OR

UPDATE t
 SET t.ColumnName = 'NewValue'
FROM (
     SELECT TOP 30 *
     FROM TableName 
     WHERE F01 = 1 AND F02 = 1
     ORDER BY NEWID()
    )t

修改

如果您希望在更新随机选定的行后更新行ID。

您可以执行以下操作

 DECLARE @Table TABLE (ID INT);

;WITH CTE AS 
(
 SELECT TOP 30 *
 FROM TableName 
 WHERE F01 = 1 AND F02 = 1
 ORDER BY NEWID()
)
UPDATE CTE 
 SET ColumnName = 'NewValue'
OUTPUT inserted.ID INTO @Table(ID)

-- now select from the table variable 
SELECT * FROM @Table 

答案 1 :(得分:2)

DECLARE @ids AS TABLE(id INT)
INSERT INTO @ids(id) SELECT TOP(2) ID FROM Chess.dbo.Sheet1$ WHERE F01 = 1 AND F02 = 1 ORDER BY NEWID()
UPDATE Chess.dbo.Sheet1$ SET F01 = 'A'
WHERE ID IN (
SELECT id
FROM @ids)

答案 2 :(得分:0)

您可以使用以下脚本,但它会逐个更新。所以你应该两次执行脚本来更新两行。

   Update T
        Set F01 = 'A'
    Output Deleted.ID
    From Test T
    Where ID IN (Select ROUND(((Max(ID) - Min(ID) -1) * RAND() + Min(ID)), 0) 
                From Test 
                Where F01 = '1' And F02 = '1')