订单查询及订单明细
订单表
OrderId
CustomerId
Date
Total
OrderDetails
OrderDetailId
OrderId
ProductId
Quantity
UnitPrice
我正在使用订单查询
INSERT INTO dbo.Orders (CustomerId, Date, Total)
VALUES (1, 2011-04-10, 50000);
我多次执行 OrderDetail 查询。
DECLARE @OrderID int
SET @OrderID = SCOPE_IDENTITY()
INSERT INTO dbo.OrderDetail (OrderId,ProductDescriptionId,Quantity,UnitPrice)
VALUES (@OrderID,11,2,50000)
这里的问题是,在我第二次执行此查询后,@OrderID 的值发生了变化,并且不再与 Orders 表中的外键匹配。那么我应该怎么做才能解决这个问题?
Order Table
OrderId
CustomerId
Date
Total
OrderDetails
OrderDetailId
OrderId
ProductId
Quantity
UnitPrice
i am using Order query
INSERT INTO dbo.Orders (CustomerId, Date, Total)
VALUES (1, 2011-04-10, 50000);
I am executing OrderDetail query many times.
DECLARE @OrderID int
SET @OrderID = SCOPE_IDENTITY()
INSERT INTO dbo.OrderDetail (OrderId,ProductDescriptionId,Quantity,UnitPrice)
VALUES (@OrderID,11,2,50000)
The problem here is that the value of @OrderID changes, and no longer matches the foreign key from the Orders table after i execute this query for the second time. so what should i do to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
I.
您必须使用相同的连接来:插入订单:
检索
SCOPE_IDENTITY()
并存储它在代码中的某个地方(您没有提供 .NET 代码,因此我可以给您更准确的建议):II.
然后(是否相同连接):插入 OrderDetails 使用:
--连接:
-- 或参数:
I.
You have to use the same connection to:Insert the Order:
Retrieve
SCOPE_IDENTITY()
and store it in some place in your code (you havn't supplied the .NET code, so I could give you more precise advice) :II.
Then (same connection or not):Insert OrderDetails using:
-- concatenation:
-- or Parameters:
如果您的订单详细信息作为身份字段,那么当您调用 INSERT INTO dbo.OrderDetail 时,它将更改 SCOPE_IDENTITY。您需要为每个订单条目设置或 @OrderID 一次,并且在向订单表添加另一列之前不要再次调用 SCOPE_IDENTITY。
If your order detail as an identity field, then when you call INSERT INTO dbo.OrderDetail it's going to change SCOPE_IDENTITY. You'd need to set or @OrderID once for each Order entry and not call SCOPE_IDENTITY again until you've added another column to your Orders table.