我有一个包含一个表的数据库,我有3个选择SQL语句。
这些选择项目具有不同的条件。如何合并这个3 SQL命令的答案?
我不想将它们逐行合并到数据表中。还有其他办法吗?
有点像这样......
OleDbCommand cmd = new OleDbCommand("select top "+ cont0 +" * from (select * from db where tablenumber=0) order by ID ASC", mycon);
OleDbDataAdapter adapt=new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
DataTable dttemp = new DataTable();
adapt = new OleDbDataAdapter(cmd);
adapt.Fill(dt);
cmd = new OleDbCommand("select top "+ cont1 +" * from (select * from db where tablenumber=1) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
if (cont2 != 0)
{
cmd = new OleDbCommand("select top " + cont2 + " * from (select * from db where tablenumber=2) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
dttemp = new DataTable();
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
}
if (cont3 != 0)
{
cmd = new OleDbCommand("select top " + cont3 + " * from (select * from db where tablenumber=3) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
dttemp = new DataTable();
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
}
if (cont4 != 0)
{
cmd = new OleDbCommand("select top " + cont4 + " * from (select * from db where tablenumber=4) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
dttemp = new DataTable();
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
}
if (cont5 != 0)
{
cmd = new OleDbCommand("select top " + cont5 + " * from (select * from db where tablenumber=5) order by ID ASC", mycon);
adapt = new OleDbDataAdapter(cmd);
dttemp = new DataTable();
adapt.Fill(dttemp);
foreach (DataRow row in dttemp.Rows)
{
dt.Rows.Add(row.ItemArray);
}
}
答案 0 :(得分:0)
您可以像这样合并它们:
"select * from
(select *, row_number() over(partition by field order by id) as rn
from table1 where field in(0, 5, 9)) t
where rn <= " + cont
修改强>
string command = "select * from ( select top "+ cont0 +" * from db where tablenumber=0 order by ID) t union all
select * from ( select top "+ cont1 +" * from db where tablenumber=1 order by ID) t";
if (cont2 != 0)
comand += " union all select * from ( select top " + cont2 + " * from db where tablenumber=2 order by ID) t";
if (cont3 != 0)
comand += " union all select * from ( select top " + cont3 + " * from db where tablenumber=3 order by ID) t";
....
OleDbCommand cmd = new OleDbCommand(command, mycon);
OleDbDataAdapter adapt=new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
....