Retrieve output parameter of SQL statement

泄露秘密 提交于 2021-01-27 05:02:28

问题


I'm using a table with two columns, customer_id and customer_name.

customer_name is a simple varchar, customer_id is an auto incrementing primary key.

I want to use my C# application to insert a customer_name, and retrieve the value of the customer_id.

Just inserting is simply solved by using

using (SqlConnection connection = new SqlConnection(AppConstants.ConnectionString))
{
    using (SqlCommand command = new SqlCommand("INSERT INTO custom_customer (customer_name) VALUES (@name);"))
    {
        command.Parameters.Add(new SqlParameter("name", customer));
        connection.Open();
        command.ExecuteNonQuery();
        connection.Close();
    }
}

I found some documentation of the OUTPUT statement, which can be used to retrieve a value.

I think the correct syntax would be

INSERT INTO custom_customer (customer_name) 
OUTPUT Inserted.customer_id 
VALUES (@name);

And I figure I need to use

command.ExecuteReader();

But then I'm stuck. How should I go about getting the value from the query?


回答1:


First, use the ExecuteNonQuery to write operations. After execute command, you can read the parameter from Parameters collection, since you have set the parameter as a output parameter, for sample:

command.Parameters["name"].Direction = System.Data.ParameterDirection.Output;

command.ExecuteNonQuery();

object name = command.Parameters["name"].Value;

If you want to know what Id the identity column generated after the insert, you could use SCOPE_IDENTITY() sql command, and use the ExecuteScalar() to get the result of command, for sample:

int id;
using (SqlConnection connection = new SqlConnection(AppConstants.ConnectionString))
{
    string sql = @"INSERT INTO custom_customer (customer_name) 
                                        VALUES (@name); 
                   SELECT SCOPE_IDENTITY();"

    using (SqlCommand command = new SqlCommand(sql))
    {
        command.Parameters.Add(new SqlParameter("name", customer));
        connection.Open();
        id = (int) command.ExecuteScalar();
        connection.Close();
    }
}



回答2:


You can use ExecuteScalar instead

int id = (int) command.ExecuteScalar();



回答3:


You need to call ExecuteScalar() to get the ID value:

int ID= (int) Command.ExecuteScalar();



回答4:


using (SqlConnection connection = new SqlConnection(AppConstants.ConnectionString))
using (SqlCommand command = new SqlCommand("INSERT INTO custom_customer (customer_name) VALUES (@name);SELECT SCOPE_IDENTITY();"))
{
    command.Parameters.Add(new SqlParameter("name", customer));
    connection.Open();
    int id= (int)Command.ExecuteScalar();
}


来源:https://stackoverflow.com/questions/20381500/retrieve-output-parameter-of-sql-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!