简体   繁体   English

使用C#和存储过程从SQL Server检索VarChar(MAX)

[英]Retrieving VarChar(MAX) from SQL Server using C# and a stored procedure

I have a WebMethod which is called to retrieve a varchar(max) column from SQL Server. 我有一个WebMethod ,它被称为从SQL Server中检索varchar(max)列。 I create my neccessary stored procedure, which works fine in Management Studio, but when I run the below code I get an error: 我创建了必要的存储过程,该过程在Management Studio中可以正常运行,但是在运行以下代码时出现错误:

Invalid attempt to read when no data is present 没有数据时读取尝试无效

Code: 码:

[WebMethod]
public static void PopulatePopUp(string arg)
{
    var str = GlobalStatic.ExceptBlanks(arg);

    SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);

    SqlDataReader rdr = null;

    using (conn)
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            conn.Open();

            cmd.CommandText = "GetMessage_Sel";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@messageId", SqlDbType.VarChar, -1).Value = str;
            cmd.Parameters.Add("@RowCount", SqlDbType.Int).Direction = ParameterDirection.Output;

            cmd.Connection = conn;

            try
            {
                rdr = cmd.ExecuteReader();

                if (rdr.HasRows)
                {
                    string fieldValue = rdr.GetString(0);
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }

                rdr.Close();
            }
            catch (Exception err)
            {
                // handle the error
                //messageInsert = false;
            }
            finally
            { 
                conn.Close(); 
            }
        }
    }
}

Depending on the rows you expect you would need the Read method called which will actually fetch you the results, so this condition should be good as it would only move in if there is a row to read out 根据您期望的行,您将需要调用Read方法,该方法实际上将为您获取结果,因此此条件应该很好,因为只有在有要读出的行时才会移入

while(rdr.Read())
{...}

OR 要么

if(rdr.Read())
{ ...}

try this 尝试这个

                    if (rdr.HasRows)
                    {
                        while(rdr.Read())
                        {
                            string fieldValue = rdr[0].ToString();
                        }

                    }
                    else
                    {
                        Console.WriteLine("No rows found.");
                    }

That happened because you have not read next record. 发生这种情况是因为您尚未阅读下一条记录。

Change 更改

if (rdr.HasRows)
{
    string fieldValue = rdr.GetString(0);
}

to

if (rdr.Read())
{
    string fieldValue = rdr.GetString(0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM