2014-03-26 84 views
0

我在SQL(InjuryScenario和ProductTypeDet)兩個表插入主鍵標識(ID)到其它表作爲外鍵

CREATE TABLE InjuryScenario 
(

InjuryScenario_id int identity(1,1), 
InjuryScenario_name varchar(80), 
InjuryDay int, 
InjuryMonth int, 
InjuryYear int, 
InjuryDesc varchar(80), 
InjuryComments varchar(50), 
AlmostInjury int, 
InjuryInSchool varchar(20), 
ProductInjury varchar(20), 
Cause_id int, 
CauseType_id int, 
CauseChar_id int, 
Place_id int, 
PlaceType_id int, 
Username varchar(50), 
InjuryDate_id int, 
constraint pk_InjuryScenario_id primary key (InjuryScenario_id), 
constraint fk_Cause_InjuryScenario foreign key(Cause_id) references Cause(Cause_id) on delete cascade, 
constraint fk_CauseType_InjuryScenario foreign key(CauseType_id) references CauseType(CauseType_id) on delete no action, 
constraint fk_Place_InjuryScenario foreign key(Place_id) references Place(Place_id) on delete cascade, 
constraint fk_PlaceType_InjuryScenario foreign key(PlaceType_id) references PlaceType(PlaceType_id) on delete no action, 
constraint fk_Users_InjuryScenario foreign key(Username) references Users(Username) on delete cascade, 
constraint fk_InjuryDate_InjuryScenario foreign key(InjuryDate_id) references InjuryDate(InjuryDate_id) on delete cascade, 
) 


CREATE TABLE ProductTypeDet 
(
ProductCategory_id int, 
ProductType_id int, 
Product_name varchar(80), 
Brand_name varchar(80), 
Notes varchar(80), 
Manufacturer_name varchar(80), 
Launch_Date date, 
ProdTypeDesc varchar(80), 
ProductInjury varchar(20), 
Status_id int, 
SafetyAct_id int, 
InjuryScenario_id int foreign key references InjuryScenario(InjuryScenario_id), 
constraint fk_ProductCategory_ProductTypeDet foreign key(ProductCategory_id) references ProductCategory(ProductCategory_id) on delete cascade, 
constraint fk_ProductType_ProductTypeDet foreign key(ProductType_id) references ProductType(ProductType_id) on delete no action, 
constraint fk_ProductStatus_ProductTypeDet foreign key(Status_id) references ProductStatus(Status_id) on delete cascade, 
constraint fk_SafetyAct_ProductTypeDet foreign key(SafetyAct_id) references Product(SafetyAct_id) on delete no action 
) 
在VS

我有從用戶到該表中插入數據插入功能。

我建立SQL TRIGGER-

CREATE TRIGGER tr_InjuryScenario_ForInsert 
ON InjuryScenario 
FOR INSERT 
AS 
BEGIN 

DECLARE @Id int 
SELECT @Id = InjuryScenario_id from inserted 

INSERT INTO ProductTypeDet(InjuryScenario_id) 
values(@Id) 

END 

我有一個問題,在ProductTypeDet表兩行created-一個從觸發(剛好與InjuryScenario_id和其他coloumns爲空),並從另一個在vs中插入函數(從用戶選擇填充顏色,InjuryScenario_id爲空)。 我如何將這兩行連接成一個?

回答

0

你永遠不會寫這樣的觸發器!插入和刪除的表可能包含多行,並且您試圖將該值設置爲標量變量。 (順便說一句,你應該用多個記錄插入/更新或刪除來測試觸發器)使用基於集合的支持。

INSERT INTO ProductTypeDet(InjuryScenario_id) 
SELECT InjuryScenario_id from inserted 
+0

我改變了它就像你說的,仍然有ProductTypeDet表2的行... :( – user3082812

+0

如果插入兩行到原表,你shoudlhave兩排在礦井等表 – HLGEM

+0

哦,等一下我看你的應用程序也插入行,你需要關閉應用程序或者根本不需要觸發器,但是如果應用程序是唯一的地方,它們將來自於然後leav在那裏並取出觸發器,如果​​表格有時會從外部填充,然後將插入從應用程序中取出並留下觸發器。 – HLGEM