scope_identity()
withidentity columns
を主キーとして使用する例:
SQLフィドル
MS SQL Server 2008スキーマのセットアップ:
create table TradingPartner (
PartnerPK int not null identity(1,1) primary key,
SomePartnerData varchar(100)
)
create table Location(
LocationPK int not null identity(1,1) primary key,
TradingPartnerFK int not null,
SomeLocationData varchar(100),
foreign key (TradingPartnerFK) references TradingPartner (PartnerPK)
)
go
create procedure usp_insert_partner
@SomePartnerData varchar(100)
as
begin
declare @PartnerPK int
insert TradingPartner (SomePartnerData) values (@SomePartnerData)
set @PartnerPK = scope_identity()
return @PartnerPK
end
go
create procedure usp_insert_location
@TradingPartnerPK int,
@SomeLocationData varchar(100)
as
begin
declare @LocationPK int
insert Location (TradingPartnerFK, SomeLocationData)
values (@TradingPartnerPK, @SomeLocationData)
set @LocationPK = scope_identity()
return @LocationPK
end
クエリ1:
declare @PartnerPK int
exec @PartnerPK = usp_insert_partner 'Some Partner 1'
exec usp_insert_location @PartnerPK, 'Some Location 1'
exec @PartnerPK = usp_insert_partner 'Some Partner 2'
exec usp_insert_location @PartnerPK, 'Some Location 2'
select *
from Location l
join TradingPartner p on l.TradingPartnerFK = p.PartnerPK
結果:
| LOCATIONPK | TRADINGPARTNERFK | SOMELOCATIONDATA | PARTNERPK | SOMEPARTNERDATA |
----------------------------------------------------------------------------------
| 5 | 4 | Some Location 1 | 4 | Some Partner 1 |
| 6 | 5 | Some Location 2 | 5 | Some Partner 2 |