使用与ASP.NET控件SCOPE_IDENTITY() [英] Using scope_identity() with ASP.NET controls

查看:183
本文介绍了使用与ASP.NET控件SCOPE_IDENTITY()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个表单输入一些数据到一个表在我的数据库,现在我要插入的数据,并取回ID(这是一个自动编号)刚刚添加的纪录。我已经得到了部分插入工作蛮好的,我已经上涨SELECT SCOPE_IDENTITY();到那结束,但现在我需要检索返回的数字。

目前,所有这一切都与一个SqlDataSource的完成(与插入语句被放在一起,并解雇了一些C#中的codebehind文件,它从形式需要在页面上的数据)。

有没有一种快速的方法来获取该号码,把它放在一个变量?


解决方案

SqlDataSource的用途的的ExecuteNonQuery 内部,这意味着你无法直接检索该值。一种解决方法是通过一个输出参数为您SqlataSource的插入参数列表,然后通过设置在SCOPE_IDENTITY该变量返回的值。该变量的值可以从在插入事件。

这就是


  1. 添加一个名为标识的输出参数到你的SqlDataSource的插入参数声明

  2. 替换SELECT SCOPE_IDENTITY();在与INSERT语句的结束SET @Identity = SCOPE_IDENTITY();

  3. 现在的@Identity参数可以在插入事件被检索到的值如下:


      

    保护无效
      SqlDataSource1_Inserted(对象发件人,
      SqlDataSourceStatusEventArgs五){

      //读取@Identity OUTPUT参数的值
    INT lastID = e.Command.Parameters [@身份]值。
    ...


      
      

    }



I've built a form for entering some data into a table in my database, now I want to INSERT that data, and get back the ID (which is an autonumber) of the record that has just been added. I've got the INSERT part working just fine, and I've tacked "SELECT SCOPE_IDENTITY();" onto the end of that, but now I need to retrieve the returned number.

At the moment all of this is done with an SqlDataSource (with the "INSERT" statement being put together and fired by some C# in the codebehind file, which takes data from a form on the page).

Is there a quick way to grab that number and put it in a variable?

解决方案

SQLDataSource uses ExecuteNonQuery internally which means that you can't retrieve the value directly. A workaround is to pass an output parameter to your SqlataSource's insert parameters list, and then set the value returned by SCOPE_IDENTITY in that variable. The value of the variable can be retrieved from in the Inserted event.

That is,

  1. Add an output parameter called Identity to your SqlDatasource's Insert Parameters declaratively
  2. Replace "SELECT SCOPE_IDENTITY();" at the end of the insert statement with "SET @Identity = SCOPE_IDENTITY();"
  3. Now the value of the @Identity parameter can be retrieved in the "Inserted" event as follows:

    protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e) {

    //Read the value of the @Identity OUTPUT parameter
    int lastID = e.Command.Parameters["@Identity"].Value;
    ...  
    

    }

这篇关于使用与ASP.NET控件SCOPE_IDENTITY()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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