我有一串不同数量的SQL。如何将它们一起添加。净?

时间:2012-01-31 11:09:20

标签: asp.net sql-server-2008 c#-4.0

我有以下SQL查询:

SELECT * from sales WHERE cdate = (SELECT CONVERT(char(11), GETDATE(),20)) 

结果如下:

ID  NO      DATE                    AMOUNT

9   103100  2012-01-31 00:00:00.000 44.29

10  110150  2012-01-31 00:00:00.000 2360.93

11  114000  2012-01-31 00:00:00.000 63.60

12  217155  2012-01-31 00:00:00.000 717.27

如何在最后一列(amount)中添加值?

2 个答案:

答案 0 :(得分:1)

您可以在SQL Server端添加,然后使用ExecuteScalar简单地在C#代码中获取结果:

SqlCommand cmd = new SqlCommand("SELECT sum(amount) from sales WHERE cdate = (SELECT CONVERT(char(11), GETDATE(),20))", conn);
int sum = (int)cmd.ExecuteScalar();

这假设您有一个指向正确服务器的开放连接conn

答案 1 :(得分:1)

使用查询:

SELECT SUM(AMOUNT)
FROM YourTable
WHERE cdate = (SELECT CONVERT(char(11), GETDATE(),20)) 

并阅读c#:

using(SqlCommand sc = YourOpenConnection.CreateCommand())
{
  sc.CommandText = @"
  SELECT SUM(AMOUNT)
  FROM YourTable
  WHERE cdate = (SELECT CONVERT(char(11), GETDATE(),20)) 
  ";
  Console.WriteLine(sc.ExecuteScalar());
}