在C#中调用存储过程并获取其返回值,通常使用 SqlCommand 与 SqlParameter 配合。存储过程的“返回值”一般指通过 RETURN 语句返回的整型值,用于表示执行状态(如成功或错误码)。
步骤说明
1. 创建存储过程,使用 RETURN 返回一个整数值2. 在C#中设置 SqlCommand 的 CommandType 为 StoredProcedure
3. 添加一个方向为 ReturnValue 的 SqlParameter 来接收结果
4. 执行命令后,从参数中读取返回值
示例:SQL 存储过程
假设有一个判断用户是否存在的存储过程:
<font face="Courier New">
CREATE PROCEDURE CheckUserExists
@UserId INT
AS
BEGIN
IF EXISTS (SELECT 1 FROM Users WHERE Id = @UserId)
RETURN 1;
ELSE
RETURN 0;
END
</font>C# 调用代码示例
使用 SqlConnection 和 SqlCommand 调用上述存储过程:
<font face="Courier New">
using System;
using System.Data;
using System.Data.SqlClient;
<p>class Program
{
static void Main()
{
string connectionString = "your_connection_string_here";
int userId = 123;</p><pre class='brush:php;toolbar:false;'> using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("CheckUserExists", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// 添加输入参数
cmd.Parameters.Add(new SqlParameter("@UserId", userId));
// 添加返回值参数
SqlParameter returnValue = new SqlParameter();
returnValue.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(returnValue);
conn.Open();
cmd.ExecuteNonQuery(); // 执行存储过程
// 获取返回值
int result = (int)returnValue.Value;
if (result == 1)
Console.WriteLine("用户存在");
else
Console.WriteLine("用户不存在");
}
}
}}
注意事项
• RETURN 值只能是整数类型(INT),不能返回字符串或其它数据类型• 如果需要返回复杂数据(如记录集、字符串、多值),应使用 OUTPUT 参数或 SELECT 语句
• ExecuteNonQuery 适用于不返回结果集的操作;如果存储过程同时返回结果集和 RETURN 值,也可使用 ExecuteReader
基本上就这些。这种方式适合用于简单状态反馈。
