使用复合主键选择刚刚插入的记录

Jus*_*gan 6 sql sql-server sql-server-2008 composite-primary-key

我有一个带有复合主键的表,安排如下:

CREATE TABLE [dbo].[mytable]
(
    [some_id] [smallint] NOT NULL,
    [order_seq] [smallint] NOT NULL,
    -- etc...
)
Run Code Online (Sandbox Code Playgroud)

这两个列都是主键的一部分(它实际上是真实表上的4部分PK,但我为了示例而简化了它).没有列是身份.我正在编写一个存储过程,在下一个文件中order_seq为给定的内容插入一条新记录some_id:

CREATE PROCEDURE some_proc
(
    @some_id smallint,
    @newSeq smallint OUTPUT
)
AS
BEGIN
    insert into mytable (some_id, order_seq)
    values 
    (
         @some_id, 
         (select max(order_seq) + 1 from mytable where some_id = @some_id)
    )

    set @newSeq = /* order_seq of the newly-inserted row */
END
Run Code Online (Sandbox Code Playgroud)

我需要知道如何设置@newSeq.我想避免在插入后运行select查询,因为我不想遇到并发问题 - 我被禁止锁定表或使用事务(不要问).

据我所知,我不能使用,SCOPE_IDENTITY()因为没有列是一个标识.我怎样才能newSeq正确设置?

Tho*_*mas 5

首先,如果PK包含四列,则每个插入必须包含所有四列.其次,如果您使用的是SQL Server 2005+,则可以查看Output子句

Declare @NewSeqTable Table( Order_Seq int not null )

Insert MyTable( some_id, order_seq, otherPkCol, otherPkCol2 )
Output inserted.order_seq Into @NewSeqTable
Select @some_id, Max( order_seq ) + 1, otherPkCol, otherPkCol2
From MyTable
Where some_id = @some_id

Select Order_Seq
From @NewSeqTable
Run Code Online (Sandbox Code Playgroud)

OUTPUT子句(Transact-SQL)