【问题标题】:how to do an insert statement using a non auto increment ID?如何使用非自动增量 ID 执行插入语句?
【发布时间】:2011-10-07 12:15:13
【问题描述】:

对于 MySQL here 提出了同样的问题,无论如何该语法在 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 中实现相同的功能(不使用游标)?

注意:这是一个运行一次的查询,它是一个维护查询,所以竞争条件和锁不是问题。

【问题讨论】:

    标签: sql-server sql-server-2008 auto-increment


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      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 为空的情况

      【讨论】:

      • 谢谢,巴里的回答也很合适(我也给了+1)但你的回答很完美,因为这正是我所需要的。
      猜你喜欢
      • 2013-10-26
      • 2010-11-29
      • 2021-03-24
      • 2012-02-01
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多