如何将标识值插入另一个表

时间:2015-11-19 03:53:29

标签: tsql triggers insert sql-server-2012 scope-identity

我有两张桌子:

create table Clients
(
     id_client int not null identity(1,1) Primary Key,
     name_client varchar(10) not null,
     phone_client int not null
)

create table Sales
(
     id_sale int not null identity(1,1) Primary Key,
     date_sale date not null, 
     total_sale float not null
     id_clients int not null identity(1,1) Foreign Key references Clients
)

因此,让我们插入客户端(' Ralph' 00000000),id_client将为1(显然)。问题是:我如何将1插入销售?

1 个答案:

答案 0 :(得分:1)

首先 - 您无法在任何表格中将两列定义为identity - 您将收到错误

  

Msg 2744,Level 16,State 2,Line 1
  为表' Sales'指定了多个标识列。每个表只允许一个标识列。

因此,您将无法实际创建该Sales表。

id_clients中的Sales列引用 identity列 - 但本身应该定义作为身份 - 它可以获得客户的任何价值。

create table Sales
(
     id_sale int not null identity(1,1) Primary Key,
     date_sale date not null, 
     total_sale float not null
     id_clients int not null foreign key references clients(id_client)
)

-- insert a new client - this will create an "id_client" for that entry
insert into dbo.Clients(name_client, phone_client)
values('John Doe', '+44 44 444 4444')

-- get that newly created "id_client" from the INSERT operation
declare @clientID INT = SCOPE_IDENTITY()

-- insert the new "id_client" into your sales table along with other values
insert into dbo.Sales(......, id_clients)
values( ......., @clientID)