在查看存储过程时,逻辑似乎是“do stuff”,然后是select 1 as add_success
。如何检查C#中的add_success
值?
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)
// Do some stuff including inserts on a few different tables, then
INSERT INTO Table (field1, field2)
VALUES (@Val1, @Val2)
SELECT 1 AS add_success
似乎正在正确地执行所有操作,但ExecuteNonQuery
的默认返回是受影响的行,即使所有操作都成功完成,也始终为-1
。
我还尝试添加一个名为add_success
和@add_success
的返回值的参数,但这似乎也无效。
如何从存储过程向C#返回值?
答案 0 :(得分:7)
command.ExecuteScalar()
。 答案 1 :(得分:1)
尝试SqlCommand.ExecuteScalar()
方法而不是ExecuteNonQuery()
(source)。