简体   繁体   English

如何在后面的代码中从 sqldatasource.insert() 返回标识值?

[英]How to return identity value from sqldatasource.insert() in code behind?

I want to return id from insert.我想从插入中返回 id。 I found solution it's use select scope_identify.我找到了使用 select scope_identify 的解决方案。 But I want example for my code.但我想要我的代码示例。

sqlDatasource ds = new sqlDatasource();
ds.InsertCommand = "INSERT INTO Product (Name) VALUES (@Name)";
ds.InsertParameters.Add("@Name", txtName.text);
ds.Insert();

An INSERT statement cannot return anything. INSERT语句不能返回任何内容。 You have to execute as SELECT to get the scope identity.您必须作为SELECT执行才能获取作用域标识。 If you want to execute it all in one statement, you cannot do it using SqlDataSource.Insert .如果您想在一个语句中执行所有操作,则不能使用SqlDataSource.Insert 来完成 As the documentation says, it returns an int counting the rows affected by the statement.正如文档所说,它返回一个int计算受语句影响的行。

Instead, you could do something like this:相反,您可以执行以下操作:

string query = "INSERT INTO Product (Name) VALUES (@Name);Select SCOPE_IDENTITY();;";
SqlCommand sqlCommand = new SqlCommand(query, connection);
connection.Open();
string NewID= sqlCommand.ExecuteScalar();

Hope I helped!希望我有所帮助!

Having not found an acceptable answer after searching the internet for 3 days;在网上搜索 3 天后没有找到可接受的答案; this is what works:这是有效的:

Using an example of inserting a user name and returning an Id...使用插入用户名并返回 Id 的示例...

Create a stored procedure similar to this:创建一个类似这样的存储过程:

create procedure Users_Insert 
      @UserName varchar(25) 
     ,@UserId int = null output
as

insert into Users (UserName) values (@UserName)

select @UserId = scope_identity();

return @UserId;

Now in your aspx page configure your SqlDataSource as such:现在在您的 aspx 页面中,将您的 SqlDataSource 配置为:

<asp:SqlDataSource ID="dsUsers" runat="server"
        ConnectionString="<%$ ConnectionStrings:dbConnection %>"
        InsertCommand="Users_Insert" InsertCommandType="StoredProcedure" OnInserted="dsUsers_Inserted">
        <InsertParameters>
            <asp:ControlParameter ControlID="txtUserName" Name="UserName" Type="String" PropertyName="Text" />
             <asp:Parameter Name="UserId" Type="Int32" Direction="ReturnValue" />
        </InsertParameters>
    </asp:SqlDataSource>

Note the OnInserted event is wired up.请注意 OnInserted 事件已连接。

Now, in your code behind, perhaps in a Save button click event, call the insert method:现在,在您后面的代码中,也许是在保存按钮单击事件中,调用插入方法:

 dsUsers.Insert();

And finally, in the dsUsers_Inserted method that we previously wired up, get the identity:最后,在我们之前连接的 dsUsers_Inserted 方法中,获取标识:

protected void dsUsers_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
     int userId = Convert.ToInt32(e.Command.Parameters["@UserId"].Value);
}

Hope this helps at least one person.希望这可以帮助至少一个人。

Happy coding!快乐编码!

If you are working with oracle, RETURNING INTO might be what you are looking for.如果您正在使用 oracle,那么RETURNING INTO可能就是您正在寻找的。 It allows you to save your new id in an output variable.它允许您将新 ID 保存在输出变量中。 I have only used it with ExecuteNonQuery() though, so it might not work with Insert()我只将它与ExecuteNonQuery()一起使用,所以它可能不适用于Insert()

If you are working with sql developer, OUTPUT might help, though I have not used that one myself yet.如果您正在使用 sql 开发人员,则OUTPUT可能会有所帮助,尽管我自己还没有使用过。

The exact answer, which is difficult to find, is here: SQLDataSourceIdentity Post很难找到的确切答案在这里: SQLDataSourceIdentity Post

Which refers user here: Retrieving the Just-Inserted ID of an IDENTITY Column Using a SqlDataSource Control此处引用用户: Retrieving the Just-Inserted ID of an IDENTITY Column Using a SqlDataSource Control

Step 1 - add an Output Parameter步骤 1 - 添加输出参数

 <asp:Parameter Direction="Output" Name="NewID" Type="Int32" />

Step 2 - Add additional statement after insert command in SqlDataSource InsertCommand步骤 2 - 在 SqlDataSource InsertCommand 中的插入命令之后添加附加语句

SELECT @NewID=Scope_Identity()

Step 3 - Retrieve inserted value in SqlDataSource_Inserted event handler步骤 3 - 在 SqlDataSource_Inserted 事件处理程序中检索插入的值

e.command.Parameters("@NewID").value.tostring

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM