如何使用非自动递增 ID 执行插入语句?

发布于 2024-11-25 01:48:12 字数 561 浏览 1 评论 0原文

对于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静谧幽蓝 2024-12-02 01:48:12

即使您多次运行它,这也会起作用:

insert into MyTable(MyId, MyValue)
  select (select isnull(max(MyId), 0) from MyTable) + -- avoid duplicated keys, if you repeat this insert again
         row_number() over(order by MyAnotherValue),
         MyAnotherValue
    from AnotherTable

isnull() 函数涵盖 MyTable 为空时的情况

This will work, even if you run it more than once:

insert into MyTable(MyId, MyValue)
  select (select isnull(max(MyId), 0) from MyTable) + -- avoid duplicated keys, if you repeat this insert again
         row_number() over(order by MyAnotherValue),
         MyAnotherValue
    from AnotherTable

The isnull() function covers the case when MyTable is empty

拥抱我好吗 2024-12-02 01:48:12

您可以使用 Row_Number() 来实现此目的

Insert Into dbo.AnotherTable (Col1, Col2)
Select Row_Number() Over(Order By SomeColumn),
       SomeColumn

From dbo.YourTable

You can achieve this by using Row_Number()

Insert Into dbo.AnotherTable (Col1, Col2)
Select Row_Number() Over(Order By SomeColumn),
       SomeColumn

From dbo.YourTable
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文