问题
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