CREATE
TABLE Customers(CustomerID int IDENTITY(1,1) PRIMARY KEY,FirstName nvarchar(45),LastName nvarchar(45),Address nvarchar(45))
CREATE
TABLE Orders(OrderID int IDENTITY(1,1) PRIMARY KEY,OrderDate date,CustomerID int FOREIGN KEY REFERENCES [dbo].[Customers](CustomerID))
CREATE
TABLE CustomersOrders(OrderID int FOREIGN KEY REFERENCES [dbo].[Orders](OrderID),ProductName nvarchar(45),Quantity nvarchar(45),Price nvarchar(45),TotalPrice int)
如何创建STORED PROCEDURE以根据[dbo] .Customers)在Orders和CustomersOrders两个表中插入数据。
客户表已输入5 CustomerID
的数据我的数据库是第一个表父,第二个是子。第三是第二桌的孩子。我想
根据CustomerID在最后两个表中插入数据。必须添加数据
特别是customerid。
答案 0 :(得分:0)
Try this
CREATE TABLE Customers
(
CustomerID INT IDENTITY(1, 1) PRIMARY KEY,
FirstName NVARCHAR(45),
LastName NVARCHAR(45),
Address NVARCHAR(45)
)
CREATE TABLE Orders
(
OrderID INT IDENTITY(1, 1) PRIMARY KEY,
OrderDate DATE,
CustomerID INT FOREIGN KEY REFERENCES [dbo].[Customers](CustomerID)
)
CREATE TABLE CustomersOrders
(
OrderID INT FOREIGN KEY REFERENCES [dbo].[Orders](OrderID),
ProductName NVARCHAR(45),
Quantity NVARCHAR(45),
Price NVARCHAR(45),
TotalPrice INT
)
DECLARE @FirstName NVARCHAR(45)='John',
@LastName NVARCHAR(45)='Smiths',
@Address NVARCHAR(45)='46 as str',
@OrderDate DATE=getdate(),
@ProductName NVARCHAR(45)='p1',
@Quantity NVARCHAR(45)='1',
@Price NVARCHAR(45)='30',
@TotalPrice INT=30
BEGIN
INSERT INTO Customers
(FirstName,
LastName,
Address)
VALUES (@FirstName,
@LastName,
@Address);
INSERT INTO Orders
(OrderDate,
CustomerID)
VALUES (@orderdate,
@@IDENTITY)
INSERT INTO CustomersOrders
(OrderID,
ProductName,
Quantity,
Price,
TotalPrice)
VALUES (@@IDENTITY,
@ProductName,
@Quantity,
@Price,
@TotalPrice)
SELECT *
FROM customers
SELECT *
FROM Orders
SELECT *
FROM CustomersOrders
END