2015-11-19 44 views
0

我有兩個表:如何插入標識值到另一個表

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 
) 

所以,讓我們插入到客戶端(「拉爾夫」,00000000),該id_client將是1(明顯)。問題是:我如何將1插入銷售?

回答

1

首先 - 你不能有兩列在任何表定義爲identity - 你會得到

消息2744,級別16,狀態2,行指定1個
多重身份列的錯誤表'銷售'。每個表只允許有一個標識列。

因此,您將無法實際創建Sales表。

Sales引用一個identity列中的id_clients列 - 但其本身,它應該被定義爲身份 - 它得到任何價值你的客戶了。

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) 
+1

我沒有注意到我在表Sales中留下了id_clients作爲Identity,感謝您的意見。解決方案非常簡單: 插入銷售值(......,(從客戶端選擇id_clients))。 非常感謝,我的朋友。你搖滾:D – RalphVB

+0

對不起,我解決這個問題的正確方法是用IDENT_CURRENT:D – RalphVB

+0

@RalphVB:我建議你使用'SCOPE_IDENTITY'而不是'IDENT_CURRENT' –