如何检查SqlDataReader中的变量是什么?

时间:2016-12-28 09:45:22

标签: c# sql-server stored-procedures

我是C#的新手,并编写了用于调用SQL Server存储过程的代码:

using (SqlConnection con = new SqlConnection(Connection))
{
    using (SqlCommand cmd = new SqlCommand("CheckValidbehzad", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add("@p_bank", SqlDbType.VarChar).Value = p_bank;
        cmd.Parameters.Add("@p_pay_date", SqlDbType.VarChar).Value = p_pay_date;
        cmd.Parameters.Add("@p_bill_id", SqlDbType.VarChar).Value = p_bill_id;
        cmd.Parameters.Add("@p_payment_id", SqlDbType.VarChar).Value = p_payment;
        cmd.Parameters.Add("@p_ref_code", SqlDbType.VarChar).Value = p_ref_code;
        cmd.Parameters.Add("@p_branch", SqlDbType.VarChar).Value = p_branch;
        cmd.Parameters.Add("@p_channel_type", SqlDbType.VarChar).Value = p_channel;
        cmd.Parameters.Add("@p_send_date", SqlDbType.VarChar).Value = p_send_date;

        con.Open();
        reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            //TempCode = reader["PaymentID"].ToString();
        }
    }
}

该存储过程有时会在结果中返回ErrorNumber,有时会返回PaymentID。我该如何检查这种情况?

if( reader has ErrorNumber field) then
    do something
else
    do something else

谢谢大家。

2 个答案:

答案 0 :(得分:0)

不确定如何区分返回的这两列 - 如果列存在或缺失(取决于具体情况),则可以检查列是否存在:

while (reader.Read())
{
    try
    {
        int paymenIdPos = reader.GetOrdinal("PaymentID");

        // if found --> read payment id 
        int paymentID = reader.GetInt32(paymenIdPos);
    }
    catch(IndexOutOfRangeException)
    {
        // if "PaymentID" is not found --> read the "ERrorNumber"
        int errorCode = reader.GetInt32("ErrorNumber");
    }           
}

答案 1 :(得分:0)

你可以像Marc_s建议的那样检查GetOrdinal,或者像这样:

if (reader.GetSchemaTable().Select("ColumnName = 'PaymentId'").Length > 0)
{
    //do something here with pamynet
}
else if (reader.GetSchemaTable().Select("ColumnName = 'ErrorNumber'").Length > 0)
{
     //do your stuff here with error number
}