如何正确使用Scope_Identity C# [英] How Do I Correctly Use Scope_Identity C#

查看:134
本文介绍了如何正确使用Scope_Identity C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我有以下代码,似乎无法正确使用SCOPE_IDENTITY。我需要找到ID列,以便我可以使用它将数据插入到我的sql表中。



Hi all i have the following piece of code and cant seem to use SCOPE_IDENTITY correctly. I need to find the ID column so i can use it to insert data into my sql table.

SqlCommand myCommand = new SqlCommand("INSERT INTO cas_user_ext(x_id, fullname, email, name) VALUES(@x_id, @fullname, @email, @name) SET @Identity = SCOPE_IDENTITY();",
sqlcon.Connection);
//int x_id = System.Convert.ToInt32(myCommand.ExecuteScalar());
decimal decimalx_id = (decimal)myCommand.ExecuteScalar();
int x_id = (int)decimalx_id;
myCommand.Parameters.Add("@Name", Environment.UserName);
myCommand.Parameters.Add("@identity", x_id);
myCommand.Parameters.Add("@fullname", textBox1.Text);
myCommand.Parameters.Add("@email", textBox2.Text);
//primarypin = myReader["primarypin"].ToString();
//secondarypin = myReader["secondarypin"].ToString();
myCommand.ExecuteNonQuery();





如果有人可以帮助我。我已经阅读了无数的帮助文章并阅读了很多页面,但我似乎无法使其正常工作。



If anyone could please assist me. I have gone through countless help articles and read up on so many pages but i cant seem to get it working.

推荐答案

在插入之前不要创建标识。 SQL Server将为您处理。也不要插入标识栏。



原始解决方案:

You don't create the identity before the insert. SQL Server will handle that for your. Also don't insert the identity column.

Original Solution:
using (SqlConnection sqlcon = new SqlConnection("Server")) {
	using (SqlCommand myCommand = new SqlCommand("INSERT INTO cas_user_ex(fullname, email, name) VALUES(@fullname, @email, @name); SELCET SCOPE_IDENTITY();", sqlcon)) {
		myCommand.Parameters.Add("@Name", Environment.UserName);
		myCommand.Parameters.Add("@fullname", textBox1.Text);
		myCommand.Parameters.Add("@email", textBox2.Text);

		int iNewRowIdentity = Convert.ToInt32(myCommand.ExecuteScalar());
		}
	}





修订后的解决方案:



Revised Solution:

using (SqlCommand myCommand = new SqlCommand("INSERT INTO cas_user_ex(fullname, email, name) VALUES(@fullname, @email, @name); SELCET SCOPE_IDENTITY();", sqlcon.Connection)) {
	myCommand.Parameters.Add("@Name", Environment.UserName);
	myCommand.Parameters.Add("@fullname", textBox1.Text);
	myCommand.Parameters.Add("@email", textBox2.Text);

	int iNewRowIdentity = Convert.ToInt32(myCommand.ExecuteScalar());
	}


这篇关于如何正确使用Scope_Identity C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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