关于后面代码中的SCOPE_IDENTITY()值 [英] Regarding SCOPE_IDENTITY() value in code behind
本文介绍了关于后面代码中的SCOPE_IDENTITY()值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
存储过程:
Store Procedure:
ALTER PROCEDURE [dbo].[module_add]
-- Add the parameters for the stored procedure here
@Module varchar(50),
@ModuleId int output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
insert into bugreporter_Module(Module) values(@Module);
if(scope_identity()>=1)
select @ModuleId = SCOPE_IDENTITY();
else
select @ModuleId=0;
return @ModuleId;
END
////代码背后,我正在使用以下代码插入:-
////code Behind I am using following code to insert:-
DataTable dtInsert = new DataTable();
string connectionString = WebConfigurationManager.ConnectionStrings["bugreportconstring"].ToString();
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("module_add", cn);
cmd.Parameters.AddWithValue("@Module", ModuleName);
cmd.Parameters.AddWithValue("@ModuleId", 0);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtInsert);
cn.Close();
return dtInsert;
//这里我要最后插入的值...
//我该如何获取....
//here i want the last inserted value...
// how can i get....
推荐答案
您需要一点点更改代码.
You need to change your code behind little bit.
DataTable dtInsert = new DataTable();
string connectionString = WebConfigurationManager.ConnectionStrings["bugreportconstring"].ToString();
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("module_add", cn);
cmd.Parameters.AddWithValue("@Module", "test");
SqlParameter outparam =new SqlParameter("@ModuleId",SqlDbType.Int);
outparam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outparam);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
cn.Close();
Get more info from here[^]
Hope it helps.
这篇关于关于后面代码中的SCOPE_IDENTITY()值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文