SQL

检索SQL语句的输出参数

发布于 2021-06-04 17:01:04

我使用的表格有两列,customer_idcustomer_name

customer_name是一个简单的varcharcustomer_id是一个自动递增的主键。

我想使用C#应用程序插入customer_name,并检索的值customer_id

只需插入即可,只需使用即可解决

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();
    }
}

我找到了该OUTPUT语句的一些文档,这些文档可用于检索值。

我认为正确的语法是

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

我认为我需要使用

command.ExecuteReader();

但是后来我被困住了。我应该如何从查询中获取值?

关注者
0
被浏览
52
1 个回答
  • 面试哥
    面试哥 2021-06-04
    为面试而生,有面试问题,就找面试哥。

    首先,使用ExecuteNonQuery进行写操作。执行命令后Parameters,由于已将参数设置为样本的输出参数,因此可以从集合中读取参数:

    command.Parameters["name"].Direction = System.Data.ParameterDirection.Output;
    
    command.ExecuteNonQuery();
    
    object name = command.Parameters["name"].Value;
    

    如果想知道Id插入后生成的标识列,可以使用SCOPE_IDENTITY()sql命令,并使用ExecuteScalar()获得命令的结果,例如:

    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();
        }
    }
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看