是否可以为 select 中的每一行更新一个变量
Is it possible to update a variable for each row in select
在MySQL中可以像
一样轻松完成
set @var= (select value from my_sequence);
insert into new_table (id, name)
select @var := @var + 1, name from old_table;
但我找不到在 SQL 服务器中做同样事情的方法。可能吗?
有哪些替代方案?
只需使用ROW_NUMBER
:
DECLARE @Var int = (SELECT [value] FROM dbo.my_sequence WITH (UPDLOCK));
--Ensure the row can't be used while we're doing it, as I assume that
--the value would be updated later with the new sequence value
INSERT INTO dbo.new_table (id, name)
SELECT ROW_NUMBER() OVER (ORDER BY {Column to Order By}) + @Var,
[name]
FROM dbo.old_table;
你甚至可以在没有变量的情况下实现这一点:
INSERT INTO dbo.new_table (id, name)
SELECT ROW_NUMBER() OVER (ORDER BY {Column to Order By}) + ms.[value],
ot.[name]
FROM dbo.old_table ot
CROSS JOIN dbo.my_sequence ms WITH (UPDLOCK);
作为旁注,语法 SELECT @Variable = @Variable + ... FROM
是 SQL 服务器中的 documented antipattern,应避免使用。
在MySQL中可以像
一样轻松完成set @var= (select value from my_sequence);
insert into new_table (id, name)
select @var := @var + 1, name from old_table;
但我找不到在 SQL 服务器中做同样事情的方法。可能吗? 有哪些替代方案?
只需使用ROW_NUMBER
:
DECLARE @Var int = (SELECT [value] FROM dbo.my_sequence WITH (UPDLOCK));
--Ensure the row can't be used while we're doing it, as I assume that
--the value would be updated later with the new sequence value
INSERT INTO dbo.new_table (id, name)
SELECT ROW_NUMBER() OVER (ORDER BY {Column to Order By}) + @Var,
[name]
FROM dbo.old_table;
你甚至可以在没有变量的情况下实现这一点:
INSERT INTO dbo.new_table (id, name)
SELECT ROW_NUMBER() OVER (ORDER BY {Column to Order By}) + ms.[value],
ot.[name]
FROM dbo.old_table ot
CROSS JOIN dbo.my_sequence ms WITH (UPDLOCK);
作为旁注,语法 SELECT @Variable = @Variable + ... FROM
是 SQL 服务器中的 documented antipattern,应避免使用。