在CodeBehind C#TSQL中访问SCOPE_IDENTITY()

时间:2015-07-08 12:42:43

标签: c# sql .net tsql azure

我试图检索SCOPE_IDENTITY()并将其放在我可以在代码隐藏中访问的参数中。我的.aspx:

<asp:sqldatasource
    id="SqlDataSource1"
    runat="server"
    connectionstring="<%$ ConnectionStrings:myString %>"
    insertcommand="INSERT INTO [CountyHelp](County,City)
    VALUES (@County,@City) ;SELECT @Id = SCOPE_IDENTITY()">
    <insertparameters>      
          <asp:formparameter name="County"  formfield="County" />
          <asp:formparameter name="City"  formfield="City" />
          <asp:parameter Direction="Output"  Name="Id" Type="Int32" />             
    </insertparameters>     

然后在此代码中访问它:

protected void btn_send_Click(object sender, SqlDataSourceStatusEventArgs e)
{
    string sID = e.Command.Parameters["@Id"].Value.ToString();
    SqlDataSource1.Insert();
    Response.Redirect("documentsnew.aspx?id=" + sID);
}

也许是我的按钮代码没有发送参数值:

     <asp:button
       id="Button1"
       runat="server"
       text="Add Help"
       onclick="btn_send_Click" 
       />  

1 个答案:

答案 0 :(得分:2)

您获得的错误是因为您使用错误的EventArgs进行按钮Click事件。使用常规EventArgs进行Click事件,然后查看会发生什么。

您可以通过处理SqlDataSources Inserted事件来获取Scope_Identity 所以

<asp:sqldatasource
id="SqlDataSource1"
OnInserted ="On_Inserted"
runat="server"
connectionstring="<%$ ConnectionStrings:myString %>"
insertcommand="INSERT INTO [CountyHelp](County,City)
VALUES (@County,@City) ;SELECT @Id = SCOPE_IDENTITY()">
<insertparameters>      
      <asp:formparameter name="County"  formfield="County" />
      <asp:formparameter name="City"  formfield="City" />
      <asp:sessionparameter Direction="Output"  Name="Id" Type="Int32" />             
</insertparameters>
</asp:sqldatasource>

然后

protected void btn_send_Click(object sender, EventArgs e)
{

     SqlDataSource1.Insert();

}

protected void On_Inserted(Object sender, SqlDataSourceStatusEventArgs e) 
{
    string sID = e.Command.Parameters["@Id"].Value.ToString();
      Response.Redirect("documentsnew.aspx?id=" + sID);
}