Leonardo Ibanez
Leonardo Ibanez

Reputation: 1

Inserting rows of data into 2 SQL tables by using a primary and foreign key

I have a database where I've built 2 tables: "client_info", and "client_hobbies". In client_info, there are 3 columns: client_id, client_firstname, and client_lastname. In client_hobbies there are 2 columns: client_id and hobby.

I've made the client_id in the client_info table the primary and a surrogate key. And I've made the client_id in the 2nd table the reference key to the first table. I want to write a statement/statements where I can insert into both tables by using the client_id.

For example: I want to insert new clients, and at the same time insert their hobby.

Huge thanks you to anyone that can help me. I am using MS SQL Server 2014.

Upvotes: 0

Views: 39

Answers (1)

McNets
McNets

Reputation: 10807

Use 2 commands separated by semicolon:

INSERT INTO client_info (client_id, client_firstname, client_lastname)
VALUES (@client_id, @client_firstname, @client_lastname);
INSERT INTO client_hobbies (client_id, hobby)
VALUES (@client_id, @hobby);

Upvotes: 1

Related Questions