如何使用非自增ID进行插入语句?

3

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中实现相同目的的方法(不使用游标)?

注意:这是一次性运行的查询,是维护查询,因此竞争条件和锁定不是问题。

2个回答

4
这将会有效,即使你运行多次:
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为空的情况。

谢谢,Barry的回答也很恰当(我在那里也点了+1),但是你的回答更完美,因为它正好是我需要的。 - UnDiUdin

3

您可以使用Row_Number()来实现。

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

From dbo.YourTable

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接