C#中的SQL输出参数

本文关键字:参数 输出 SQL 中的 | 更新日期: 2023-09-27 18:10:09

我正试图从Microsoft SQL Server stored procedure中获取一个值。我总共需要返回两个值。正如您在下面看到的,其中一个可以通过返回访问,另一个可以由输出参数访问。我在WPF(C#(:中运行此代码

    public int InsertCustomerEntranceLogWithOptions(String cardNumber,int buy, int score, out int logID)
    {
        SqlCommand command = new SqlCommand(
            @"
            --declare @id int, @logID int                    
            exec @res = Insert_CustomerEntranceLog_WithOptions 
                @cardNumber, @buy, @score, @logID
            --set @logID = @id",
            myConnection);
        command.CommandType = CommandType.Text;
        command.Parameters.Add("@cardNumber", SqlDbType.NVarChar).Value = cardNumber;
        command.Parameters.Add("@buy", SqlDbType.Int).Value = buy;
        command.Parameters.Add("@score", SqlDbType.Int).Value = score;
        command.Parameters.Add("@logID", SqlDbType.Int).Value = 0;
        command.Parameters["@logID"].Direction = ParameterDirection.Output;      
        command.Parameters.Add("@res", SqlDbType.Int).Value = 0;
        command.Parameters["@res"].Direction = ParameterDirection.Output;
        int res = (int)RunNonQuery(command);
        logID = (int)command.Parameters["logID"].Value;
        return res;
    }

RunNonQuery方法为:

    public Object RunNonQuery(SqlCommand command, String returnVariableName = "@res")
    {
        Object result = null;
        if (openConnection())
        {
            try
            {
                command.ExecuteNonQuery();
                if (returnVariableName.Length != 0)
                {
                    result = command.Parameters[returnVariableName].Value;
                    //command.Dispose();
                }
                else
                {
                    //command.Dispose();
                    return 1;
                }
            }
            catch (TimeoutException ex)
            {
                //Log
            }
            catch (Exception ex)
            {
                Utility.LogExceptionError(ex, 1, 1, 1);
                //throw ex;
            }
            closeConnection();
        }

        return result;
    }

我确信我的RunNonQuery工作正常。我经常测试它。但是当我使用InsertCustomerEntranceLogWithOptions方法时,我会得到错误

An unhandled exception of type 'System.IndexOutOfRangeException' 
occurred in System.Data.dll
Additional information: An SqlParameter with ParameterName 'logID' 
is not contained by this SqlParameterCollection.

我似乎没有添加SqlParameter,但正如您所看到的,插入了LogID。怎么了?我还删除了SQL命令中的注释,然后运行它,但steel我看到了错误。

C#中的SQL输出参数

似乎忘记了sql参数的@前缀:

logID = (int)command.Parameters["@logID"].Value

可能是您的logID = (int)command.Parameters["logID"].Value;无法访问logId,因为它应该命名为@logID,正如您添加的那样:

command.Parameters.Add("@logID", SqlDbType.Int).Value = 0;
command.Parameters["@logID"].Direction = ParameterDirection.Output; 

和"@"必须是参数名称的一部分-是否需要在SqlParameter名称前面添加@?

@丢失,更新如下

logID = (int)command.Parameters["@logID"].Value;