SQL 插入行,但返回该行中的项

本文关键字:插入 SQL 返回 | 更新日期: 2023-09-27 18:32:30

使用 c#、Visual Studio、razor html 和 asp.net,我有一个订单表,它将客户编号保存在ecustoemr_id,然后它自动递增order_id字段,我需要选择刚刚插入的行的订单 ID。 我不能只从该客户编号中选择所有,因为客户将有多个订单 ID。 以下是我将客户 ID 保存到数据库的方式, 我需要将刚刚创建的行中的订单 ID 打印到变量中。我花了几个小时在谷歌上搜索,找到了PHP的答案,但没有使用C#和 asp.net提前致谢

string sql = "insert into orders (User_ID) values ('" + Request["UserID"] + "')";
var rst1 = db.Query(sql);

SQL 插入行,但返回该行中的项

尝试这样的事情:

string query = "INSERT INTO [Table] (id) OUTPUT INSERTED.ID VALUES (id value)";
SqlCommand com = new SqlCommand(query, dbconnection);
string value;
value = com.ExecuteScalar().ToString();

在这里阅读: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx

SCOPE_IDENTITY的替代方法是输出。像这样:

DECLARE @OrderOutput TABLE (ID INT NOT NULL)
insert into orders (User_ID) 
OUTPUT Inserted.OrderId INTO @OrderOutput(ID)
values ('" + Request["UserID"] + "')"
SELECT ID from @OrderOutput