我可以获取刚刚插入的数据的ID吗? [英] Can I get the ID of the data that I just inserted?

查看:100
本文介绍了我可以获取刚刚插入的数据的ID吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想按用户的顺序将产品放入数据库中,查询如下:

So I want to put a product in an order from an user in the database and the query goes as follows:

INSERT INTO [ dbo]。[Order](UserID,To_Adress,OrderDate,TravelTime,ItemCount,Status,TotalPrice)
VALUES(1, BIKINI BOTTOM, 20191030 15:00:00, 20191030 15:35:00 ',1,'InTheMaking',7.50)

在我输入订单后,我想把产品和数据库中的订单,但我必须获取我刚刚创建的 OrderID 。有没有办法从我刚下的订单中获得 OrderID

After I put in the order I want to put the connection between the product and the order in the database but I have to get the OrderID that I just made. Is there a way to get the OrderID from the order that I just made?

插入[dbo]。[Order_Product](OrderID,ProductID)
值(?[dbo]。[Order] .OrderID ?, 12)

编辑:

好的,所以基本上 SCOPE_IDENTITY 是获取方法它从我的数据库中删除,但是如何在第二次 INSERT 中使用 SCOPE_IDENTITY ,同时仍在同一查询中?我是否只需要为此进行2个单独的查询?

Okay, so basically SCOPE_IDENTITY is the way to get it out of my database, but how do I use the SCOPE_IDENTITY in a second INSERT while still being in the same query? Do I just have to make 2 seperate queries for that?

推荐答案

尝试使用SQL 输出 子句:

Try using the SQL OUTPUT clause:

INSERT INTO [dbo].[Order](UserID, To_Adress, OrderDate, TravelTime, ItemCount, Status, TotalPrice)
OUTPUT inserted.ID
VALUES (1, 'BIKINI BOTTOM', '20191030 15:00:00', '20191030 15:35:00', 1, 'InTheMaking', 7.50

SqlCommand.ExecuteScalar()

这篇关于我可以获取刚刚插入的数据的ID吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆