简体   繁体   English

我的范围标识从标识列检索ID时遇到一些问题

[英]I'm having some issues with my scope identity retrieving a ID from an identity column

I'm having some issues with my scope identity retrieving a ID from an identity column. 我的范围标识从标识列中检索ID时遇到一些问题。

This is my code: 这是我的代码:

cmd = connection.CreateCommand();
cmd.CommandText = "Insert Into oc_manufacturer (name, sort_order) Values(@name, @sort_order);SELECT CAST(scope_identity() AS int)";
cmd.Parameters.AddWithValue("@name", sManufacturer);
cmd.Parameters.AddWithValue("@sort_order", 0);
iManufacturerID = (int)cmd.ExecuteScalar();

cmd.ExecuteNonQuery();

This is inside a try catch. 这是一个尝试陷阱。 and it hits my catch when i step through it at the 2nd last line of code. 当我在代码的最后第二行逐步通过时,它就达到了我的目标。 I am still very new to using this scope identity. 我对使用此作用域标识仍然很陌生。 Usually i would create a whole new select statement with the same variables as my insert statement. 通常,我会使用与我的插入语句相同的变量来创建一个全新的select语句。 But that is very long so truing to get this right. 但这很长,因此很努力做到这一点。 any help? 有什么帮助吗?

Perhaps I am wrong, but you have marked your question as MySql. 也许我错了,但您已将问题标记为MySql。 In that database system, you retrieve the last inserted autoincrement value with LAST_INSERT_ID() function 在该数据库系统中,使用LAST_INSERT_ID()函数检索最后插入的自动增量值

cmd.CommandText = @"Insert Into oc_manufacturer (name, sort_order) 
                    Values(@name, @sort_order);
                    SELECT LAST_INSERT_ID()";

Also there is no need to call ExecuteNonQuery, the call to ExecuteScalar will work on both statements but will return the value of the last SELECT 同样也不需要调用ExecuteNonQuery,对ExecuteScalar的调用将在两个语句上都有效,但是将返回最后一个SELECT的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用范围标识时遇到一些麻烦 - Having some trouble using scope identity 使用scope_Identity()检索最后插入的ID - Retrieving the last inserted ID using scope_Identity() 从Sql中选择作用域标识 - Select Scope Identity from Sql 开启IDENTITY_COLUMN ID - Turning on IDENTITY_COLUMN ID 当我没有为标识列指定值时,为什么我在LINQ to SQL中获得“无法为标识列插入显式值”? - Why am I getting “Cannot insert explicit value for identity column” in LINQ to SQL when I'm not specifying a value for an identity column? 检索scope_identity时,特定强制转换无效 - Specific cast is not valid, while retrieving scope_identity 从Web应用程序检索原始用户身份 - Retrieving original user identity from web application 我在使用托管服务标识对使用 AAD 保护的 Azure 应用服务进行身份验证时遇到问题 - I'm having problems authenticating with Managed Service Identity to an Azure App Service secured with AAD HttpContext.Current.User.Identity .:身份正在从我的本地Windows登录名与我正在测试的网站登录名中提取 - HttpContext.Current.User.Identity.: Identity is pulling rom my local Windows login vs the website login I'm testing 如何使用ExecuteScalar函数和SCOPE_IDENTITY()函数检索插入的行的ID - How can I retrieve the ID of the inserted row using ExecuteScalar function and the SCOPE_IDENTITY() function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM