我通过类似这样的查询插入记录:如何检索通过插入插入的行的标识... select?
insert into tbl_xyz select field1 from tbl_abc
现在我想中检索的记录插入新生成的标识值。我如何以最小的锁定和最大的可靠性来做到这一点?
我通过类似这样的查询插入记录:如何检索通过插入插入的行的标识... select?
insert into tbl_xyz select field1 from tbl_abc
现在我想中检索的记录插入新生成的标识值。我如何以最小的锁定和最大的可靠性来做到这一点?
你可以使用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
然后,您可以查询您的插入ID的表InsertedIDs。
SELECT @@IDENTITY
这就是我以前做过的。不知道这是否会满足您的后半部分。
编辑
发现这个链接太多,但不知道这是否是一样的...
How to insert multiple records and get the identity value?
@@ IDENTITY将返回最后插入IDENTITY值,所以你有两个可能出现的问题
小心插入table_xyz时,因为这可能会改变@@ IDENTITY值触发器执行的。
tbl_abc是否有多行。 ()代替@@ IDENTITY 第2期就不好办了如果是这样那么@@ IDENTITY将只返回最后一行
问题1的标识值可以通过SCOPE__IDENTITY解决。 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
这只会retreive的身份插入最后一条记录我需要检索他们所有人 – Manu 2009-02-22 17:26:39
我正在使这个最喜欢的问题。我也想知道答案:) – RSolberg 2009-02-22 17:28:31