[英]How can I retrieve the identities of rows that were inserted through insert…select?
我通過類似於此查詢的查詢插入記錄:
insert into tbl_xyz select field1 from tbl_abc
現在,我想檢索插入記錄的新生成的IDENTITY值。 如何以最小的鎖定量和最大的可靠性做到這一點?
您可以使用OUTPUT子句獲取此信息。
您可以將信息輸出到臨時目標表或視圖。
這是一個例子:
DECLARE @InsertedIDs TABLE (ID bigint)
INSERT into DestTable (col1, col2, col3, col4)
OUTPUT INSERTED.ID INTO @InsertedIDs
SELECT col1, col2, col3, col4 FROM SourceTable
然后,您可以在表InsertedIDs中查詢所插入的ID。
@@ IDENTITY將返回您最后插入的IDENTITY值,因此您有兩個可能的問題
注意插入table_xyz時執行的觸發器,因為這可能會更改@@ IDENTITY的值。
tbl_abc是否有多於一行。 如果是這樣,則@@ IDENTITY將僅返回最后一行的標識值
可以通過使用SCOPE__IDENTITY()而不是@@ IDENTITY來解決問題1。問題2很難解決。 tbl_abc中的field1是否在tbl_xyz內定義了唯一記錄,如果這樣,您可以使用標識列從table_xyz中重新選擇數據。 還有其他使用CURSORS的解決方案,但是它們會很慢。
據我所知,在同一腳本中使用純SQL確實無法做到這一點。 但是您可以創建一個INSERT觸發器。 現在,我討厭觸發器,但這是做到這一點的一種方法。
根據您要嘗試執行的操作,可能需要先將行插入到臨時表或表變量中,然后以這種方式處理結果集。 希望有一個可以鏈接到的唯一列。
您還可以鎖定表,獲取最大鍵,插入行,然后再次獲取最大鍵並進行范圍設置。
觸發:
--Use the Inserted table. This conaints all of the inserted rows.
SELECT * FROM Inserted
臨時表:
insert field1, unique_col into #temp from tbl_abc
insert into tbl_xyz (field1, unique_col) select field1, unique_col from tbl_abc
--This could be an update, or a cursor, or whatever you want to do
SELECT * FROM tbl_xyz WHERE EXISTS (SELECT top 1 unique_col FROM #temp WHERE unique_col = tbl_xyz.unique_col)
按鍵范圍:
Declare @minkey as int, @maxkey as int
BEGIN TRANS --You have to lock the table for this to work
--key is the name of your identity column
SELECT @minkey = MAX(key) FROM tbl_xyz
insert into tbl_xyz select field1 from tbl_abc
SELECT @maxkey = MAX(key) FROM tbl_xyz
COMMIT Trans
SELECT * FROM tbl_xyz WHERE key BETWEEN @minkey and @maxkey
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.