0
votes

My c# code calls a stored procedure and passes a tvp as an argument to the storerd procedure. I need to insert the received data into several database tables.

TVP schema:
TVP_ID int PRIMARY KEY IDENTITY, Col1 int, Col2 int, Col3 int.

First, I need to insert Col1 to Table1:

Table1 schema:
Table1_ID int PRIMARY KEY IDENTITY, Col1 int

Than, I need to insert all columns into Table2.

Table2 schema:
TVP_ID int, Col1 int, Col2 int, Col3 int, Table1_ID int

where TVP_ID and Table1_ID are primary keys of TVP and Table1 tables.

How can I do that?

Thanks!

Edit: My problem is that when I have Table1 (after data was inserted to col1) the connection between TVP and Table1 is no longer exists. Key of TVP is TVP_ID, key of Table1 is Table1_ID, and I lost the connection between them.

I insert multiple rows, so once I have added multiple rows to Table1 how can I insert multiple rows to table2?

1
so what is your question? - vivek nuna
My question is how do I do that? - user3584783
you want to do where? in C#? MqSQL? in SQL Server? - vivek nuna
Sorry, I want to write the stored procedure that receives a TVP and insert the data to the tables the way I explained above - user3584783
this can help you INSERT INTO table (name) VALUES('vivek'); SELECT SCOPE_IDENTITY() get this id and insert into second table - vivek nuna

1 Answers

0
votes

When you do an insert into MSSQL, all data inserted is temporarily stored. You can acces the data by using an OUTPUT clause. In this output clause you have two ways of accessing data. Inserted.* (or specified column) and Deleted.. This way you can capture the same data that was either inserted or deleted, and route it to another table. With an Insert statement, you can only use OUTPUT inserted., with Delete only OUTPUT deleted.* and with update both (an update is after all nothing but a delete, and an insert of the same row with 1 or more cells changed)

The syntax is as follows:

Insert Into table1(table1_ID, col1)
Output inserted.tabl1_id, inserted.col1 into table2
from .... (or Values()? )

After the insert you can do an OUTPUT inserted.col1, inserted.col2 etc INTO table2. For update and delete you can use the same syntax (OUTPUT deleted.* into <2nd table>)

If you would have to copy the data to multiple tables, you can also store it in a table variable or a temp table. Note, you cant store it anything but a table, even if you know it will return just a single row. This is because while you might know it will always return 1 row, SQL doesnt and wont allow this to be a problem.