如何从C#中的存储过程中获取所选值?

Eri*_*118 2 c# sql-server stored-procedures

在查看存储过程时,逻辑似乎是"做东西",然后是select 1 as add_success.如何add_success在C#中检查该值?

using (SqlConnection connection = new SqlConnection(_connectionString)) {
  using (SqlCommand command = new SqlCommand("<sprocname>", connection)) {
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(<a parameter>); // x10 or so
    connection.Open();
    var result = command.ExecuteNonQuery();
    // result is always -1, despite the sproc doing everything it is supposed to do (modify a few different tables)
Run Code Online (Sandbox Code Playgroud)

存储过程

// Do some stuff including inserts on a few different tables, then
INSERT INTO Table (field1, field2)
VALUES (@Val1, @Val2)

SELECT 1 AS add_success
Run Code Online (Sandbox Code Playgroud)

它似乎正在正确地执行所有操作,但默认返回来自ExecuteNonQuery受影响的行,-1即使所有操作似乎都成功完成,也始终如此.

我也尝试添加一个名为返回值的参数add_success@add_success,但也出现了无法正常工作.

如何从存储过程向C#返回值?

the*_*yer 7

  1. 你需要使用command.ExecuteScalar().
  2. 结果将是结果集中第一个表的第一行.