我有两张桌子:
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插入销售?
答案 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)