使用SqlCommand时SUM(Table)不起作用

时间:2019-05-22 15:58:11

标签: c# sql-server

当我运行代码时,结果将是'Type'而不是Name的SUM。 也尝试在Reader [(“ Types”)]内进行SUM,并显示SUM(Types)。它应该显示该特定名称的金额

C#中的代码:

public void DisplayName()
{
        try
        {
            string Connection = @"Data Source=local;Initial Catalog=Project;Integrated Security=True";
            SqlConnection Connect = new SqlConnection(Connection);

            string Name;

            Console.WriteLine("\nShowing Name\n");

            Console.WriteLine("Enter name type: \n");
            country = Console.ReadLine();

            ConnectingDatabase.Open();

            string Query = "SELECT SUM(Types) FROM PersonName WHERE Name = @Name";

            SqlCommand Commands = new SqlCommand(Query, ConnectingDatabase, ConnectingDatabase.BeginTransaction());

            Commands.Parameters.Add(new SqlParameter("@Name", country));

            SqlDataReader Reader = ParaComm.ExecuteReader();

            if (Reader.Read())
            {
                Console.WriteLine("Your name is " + name + " with sum of {0}\n", Reader[("Types")]);
            }

            Reader.Close();
            ParaComm.Transaction.Commit();
            Connect.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
}

2 个答案:

答案 0 :(得分:0)

在sql中使用aggregeate函数时,应使用Group By。试试这个Sql-Command

 string Query = "SELECT SUM(Types) FROM main.Stats Group by column_name WHERE 
 Name = @Name";

答案 1 :(得分:0)

如您所知,您始终可以按列号引用一列。即0

但是,解决此问题的最简单方法是避免出现查询更改而导致列号更改的问题,这是为列提供别名。

如果您向查询添加别名,请将其更改为 SELECT SUM(Types) as TypeSum FROM PersonName WHERE Name = @Name应该会发现您可以使用Reader["TypeSum"]语法访问该值。