How to write a stored procedure to insert values into two tables with a foreign key relationship?

余生长醉 提交于 2020-01-26 04:10:08

问题


I created two tables, Employeeinfo and Employeerequests.

Table Employeeinfo can have one unique user with columns:

  • id (primary key, auto increment)
  • name
  • dep
  • address

and table Employeerequests can have multiple requests against one unique user ID with columns

  • id (primary key, auto increment)
  • CustomerID(foreign key to Employeeinfo(ID column))
  • category
  • requests.

Now I want to design a stored procedure in such a way so that I can insert values into both tables at the same time. Please help. I am very new to SQL. Thanks in advance.


回答1:


This is a bit long for a comment.

SQL Server only allows you to insert into one table in a single query. You presumably want to provide both employee and request information. So that limitation on insert is a real problem.

You can get around the limitation by creating a view combining the two table and then defining an instead of insert trigger on the view. This is explained in the documentation.

That said, you seem to not have extensive SQL knowledge. So, I would recommend simply using two separate statements, one for each table. You can wrap them in a stored procedure, if you find that convenient.




回答2:


In the stored procedure, you can use Output clause of Insert statement as:

DECLARE @MyTableVar TABLE (NewCustomerID INT);  

-- The OUTPUT clause have access to all the columns in the table, 
-- even those not part of Insert statement ex:EmployeeID.
INSERT INTO [dbo].[Employeeinfo] ([Name], [dep], [address])  
OUTPUT INSERTED.Id INTO @MyTableVar  
    SELECT 'Test', 'TestDep', 'TestAddress'

-- then make insert in child table as   
INSERT INTO [dbo].[Employeerequests] (CustomerID, category)  
    SELECT NewCustomerID, 'TestCat'
    FROM @MyTableVar

Sample code here...

Hope that helps!



来源:https://stackoverflow.com/questions/59445207/how-to-write-a-stored-procedure-to-insert-values-into-two-tables-with-a-foreign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!