SQL Server插入语句可自动插入外键

时间:2018-10-09 03:54:02

标签: sql-server ado.net

我的应用程序有两个步骤。首先,用户在ClientRelationships表中输入relationship_name,然后在ProspectInformation表中输入数据。请注意,ClientRelationships表下的Relationship_id列是ProspectInformation下的外键(FK_Relationship)。

能帮我构造一条插入语句,在其中我可以输入所有ProspectInformation数据,并使用Relationship_name将FK_Relationship匹配到Relationship_id。

例如,relationship_name = Smith Restaurant Franchise等人,而Relationship_id = 1(自动生成)。同时,promise_name =汉堡王(不为空字段),并且promise_id = 1001(自动生成)。我希望ProspectInformation表中的FK_Relationship列与Relationship_id = 1匹配。我想在ADO.Net的SqlCommand中使用此插入语句。

CREATE TABLE ClientRelationships
(
    relationship_id INT IDENTITY(1,1) PRIMARY KEY,
    relationship_name VARCHAR(25) NOT NULL UNIQUE,
); 

CREATE TABLE ProspectInformation
(
    prospect_id INT IDENTITY(1000,1) PRIMARY KEY,
    prospect_name VARCHAR(50) NOT NULL,
    prospect_street VARCHAR(25),
    prospect_city VARCHAR(25),
    prospect_state CHAR(2),
    prospect_zipCode CHAR(5),
    FK_Relationship INT  
       FOREIGN KEY REFERENCES ClientRelationships(relationship_id) 
               ON DELETE CASCADE ON UPDATE CASCADE
);

这是我的插入查询,导致错误消息4104。

INSERT INTO ProspectInformation(prospect_name, FK_Relationship) 
VALUES ('Burger King', ClientRelationships.relationship_id) 

SELECT relationship_id, relationship_name 
FROM ClientRelationships 
WHERE relationship_name = 'Smith Restaurant Franchise et al'; 

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了插入语句,它可以工作。见下文

INSERT INTO ProspectInformation(prospect_name, FK_Relationship) VALUES ('Burger King', (SELECT ClientRelationships.relationship_id FROM ClientRelationships WHERE ClientRelationships.relationship_name = 'Smith Restaurant Franchise et al'));