2011-07-18 44 views
2

MySQL here已經提出了同樣的問題,無論如何語法在SQL Server中不起作用。如何使用非自動增量ID做插入語句?

我粘貼這個問題的示例(通過簡化它),因爲它解釋了我需要的很好。

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

實現時,此會的工作,即使你運行它不止一次:

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是空

+0

謝謝,巴里的回答也是合適的(我也給了+1),但你的回答是完美的,因爲它正是我需要的。 – LaBracca

3

您可以通過使用Row_Number()

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

From dbo.YourTable