连接Sql查询

时间:2013-12-05 18:57:00

标签: c# sql-server-2008

我有一张桌子上有虫栏1,虫2,害虫3 ......虫12。下面的查询计算每列的总和

SELECT SUM(pestpopulation1)as pestpopulation1,SUM(pestpopulation2)as pestpopulation2,
  SUM(pestpopulation3)as pestpopulation3,SUM(pestpopulation4)as pestpopulation4,
  SUM(pestpopulation5)as pestpopulation5,SUM(pestpopulation6)as pestpopulation6,
  SUM(pestpopulation7)as pestpopulation7,SUM(pestpopulation8)as pestpopulation8,
  SUM(pestpopulation9)as pestpopulation9,SUM(pestpopulation10)as pestpopulation10,
  SUM(pestpopulation11)as pestpopulation11,SUM(pestpopulation12)as pestpopulation12 
FROM transformed_table.

我为c#中的每一列创建了复选框。我想要的是用户选择查询应该相应运行的选项。

例如用户检查pest1和pest2查询应该看起来像

SELECT SUM(pestpopulation1)as pestpopulation1,SUM(pestpopulation2)as pestpopulation2
FROM transformed_table.

有没有办法连接查询,因为如果我为所有可能的选项编写查询,将花费大量时间。

1 个答案:

答案 0 :(得分:2)

一个简单的例子:

string sql = "SELECT ";
if (checkBox1.Checked) sql += "SUM(pestpopulation1) as pestpopulation1, ";
if (checkBox2.Checked) sql += "SUM(pestpopulation2) as pestpopulation2, ";
// etc.
sql += "'' as dummy";  // Either this or remove the last comma.
sql += " FROM transformed_table;";

这样的事情会做

但严重的是,你应该尝试一下,然后展示你尝试过的只是为了表明你做了什么。