I have a table with a composite Primary Key, arranged something like this:
CREATE TABLE [dbo].[mytable]
(
[some_id] [smallint] NOT NULL,
[order_seq] [smallint] NOT NULL,
-- etc...
)
Both of these columns are part of the primary key (it’s actually a 4-part PK on the real table, but I’ve simplified it for the sake of the example). None of the columns are identities. I’m writing a stored proc that inserts a new record at the next order_seq for a given 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
I need to know how to set @newSeq. I’d like to avoid running a select query after the insert, because I don’t want to run into concurrency issues — I’m prohibited from locking the table or using a transaction (don’t ask).
As far as I know, I can’t use SCOPE_IDENTITY() because none of the columns is an identity. How can I set newSeq correctly?
First, if the PK contains four columns, then each insert must include all four columns. Second, you could look into the Output clause if you are using SQL Server 2005+
OUTPUT Clause (Transact-SQL)