关于后面代码中的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.