【问题标题】:Getting MAX value returned SQL command c#获取MAX值返回SQL命令c#
【发布时间】:2014-07-29 19:15:07
【问题描述】:

我正在尝试返回 MAX 值,但它一直返回 0。

string stateValue = "CA";
SqlCommand cmd = new SqlCommand("SELECT MAX(Population) FROM TestData WHERE State=" + stateValue);
cmd.Parameters.Add("@Population", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
DBConnection.Instance.execNonQuery(cmd);

int population = (int)cmd.Parameters["@Population"].Value;

DBConnection 类中,这是execNonQuery 函数:

public int execNonQuery(string sCmd, CommandType cmdType)
{
    SqlCommand cmd = new SqlCommand(sCmd, m_sqlDataBase);
    cmd.CommandType = cmdType;

    try
    {
        m_sqlDataBase.Open();
    }
    catch { }

    return cmd.ExecuteNonQuery();
}

【问题讨论】:

    标签: c# sql sql-server max


    【解决方案1】:

    参数方向与存储过程一起使用。在这里,您只是执行一个查询。您需要使用SqlCommand.ExecuteScalar 方法,因为您只会得到一个结果。它返回一个object,因此您必须在使用它之前将其转换为int

    此外,您的代码使用字符串连接来创建 SQL 查询,并且很容易出现SQL Injection。还可以考虑将using statement 与您的命令和连接一起使用。

    using (SqlCommand cmd = new SqlCommand("SELECT MAX(Popluation) FROM TestData WHERE State=@state"))
    {
        //Associate connection with your command an open it
        cmd.Parameters.AddWithValue("@state", stateValue);
        int populuation = (int)cmd.ExecuteScalar();
    }
    

    【讨论】:

    • 这行得通。我只是改变了行: int populuation = (int)cmd.ExecuteScalar();其余部分保持不变
    【解决方案2】:

    ExecuteNonQuery 调用不返回执行查询的结果。

    您可以使用ExecuteScalar 或 Execute 来取回值。

        public int execQuery(string sCmd, CommandType cmdType)
        {
            SqlCommand cmd = new SqlCommand(sCmd, m_sqlDataBase);
            cmd.CommandType = cmdType;
            try
            {
                m_sqlDataBase.Open();
    
    
                return Convert.ToInt32(cmd.ExecuteScalar());
            }
            catch { 
                 // handle your error but don't trap it here..
                 throw;
            }
        }
    

    ExecuteScalar 是获取第一个值或第一个结果集的短路。您可以使用它从查询中返回单个值,例如您的查询。

    另一种选择是使用 Execute 方法获取结果集,然后使用它来获取您所追求的值:

        public int execQuery(string sCmd, CommandType cmdType)
        {
            SqlCommand cmd = new SqlCommand(sCmd, m_sqlDataBase);
            cmd.CommandType = cmdType;
            try
            {
                m_sqlDataBase.Open();
    
                using(var dataReader = cmd.Execute())
                {
                    if (dataReader.Read())
                    {
                          return Convert.ToInt32(dataReader[0]);
                    }
                }
            }
            catch { 
                 // handle your error but don't trap it here..
                 throw;
            }
        }
    

    【讨论】:

      【解决方案3】:

      怎么样

        var sql = string.Format("SELECT MAX(Popluation) FROM TestData WHERE State='{0}'", stateValue);
        SqlCommand cmd = new SqlCommand(sql);
      

      (重要的部分是添加单引号。string.Format 是为了让它看起来更漂亮)

      【讨论】:

      • 我累了,但没有帮助。不过看起来确实很漂亮。
      猜你喜欢
      • 2012-09-28
      • 2023-03-12
      • 2017-11-02
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 2023-04-10
      相关资源
      最近更新 更多