我有下表
db_name server_name approver
cube1 server1
cube1 server2
cube2 server3
cube2 server4
我想使用以下内容更新每偶数行(假设索引从0开始)和奇数行的批准者列:
偶数(第一行):approver1 奇数(第二行):批准人
我的最终目标是使桌子看起来像这样
db_name server_name approver
cube1 server1 approver1
cube1 server2 approver2
cube2 server3 approver1
cube2 server4 approver2
我没有,没有主键/ ID列,也不打算同时包含其中一个
如何从该语句开始实现所需的内容?
UPDATE Table1
SET approvers = 'approver1'
GO
答案 0 :(得分:1)
您可以使用ROW_NUMBER和modulo,但这里需要一个id列
类似这样的东西(尚未测试)。您需要相同的“偶数”
-- get all ids from the odd numbers
With TableData As
(
SELECT ID, ROW_NUMBER() OVER (ORDER BY id ASC) AS RowNumber
FROM Table1
where (RowNumber, % 2) = 1 --odd
)
-- update the odd numbers with approver1
UPDATE Table SET approvers = 'approver1'
FROM Table1
INNER JOIN TableData ON Table1.ID = TableData.ID
答案 1 :(得分:1)
还有另一个选择...
示例
;with cte as (
Select *
,RN= Row_Number() over (Order By db_name,server_name) % 2
From YourTable
)
Update cte
Set approver = case when RN=1 then 'ApproverX' else 'ApproverY' end
更新后的表格
db_name server_name approver
cube1 server1 ApproverX
cube1 server2 ApproverY
cube2 server3 ApproverX
cube2 server4 ApproverY