如何使用非自动递增 ID 执行插入语句?
对于 MySQL 此处,无论如何,该语法在 SQL Server 中不起作用。
我将这个问题的示例粘贴到这里(通过简化),因为它很好地解释了我需要什么。
DECLARE @t1 integer
SET @t1=0;
-- MyTable is a simple Table with 2 fields "MyID" and "MyValue"
insert into MyTable
SELECT @t1 := @t1+1, --this "should" work in MySQL
MyAnotherValue
FROM AnotherTable
有没有办法在 SQL Server 中实现相同的目的(不使用游标)?
注意:这是一个运行一次的查询,它是一个维护查询,因此竞争条件和锁不是问题。
The same question has been asked for MySQL here, anyway that syntax doesn't work in SQL Server.
I paste the sample from that question (by simplifying it) here because it explains what I need very well.
DECLARE @t1 integer
SET @t1=0;
-- MyTable is a simple Table with 2 fields "MyID" and "MyValue"
insert into MyTable
SELECT @t1 := @t1+1, --this "should" work in MySQL
MyAnotherValue
FROM AnotherTable
Is there a way to achieve the same in SQL Server (without using a cursor)?
Note: this is a to be run once query, it is a maintenance query, so race conditions and locks are not an issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
即使您多次运行它,这也会起作用:
isnull()
函数涵盖MyTable
为空时的情况This will work, even if you run it more than once:
The
isnull()
function covers the case whenMyTable
is empty您可以使用 Row_Number() 来实现此目的
You can achieve this by using Row_Number()