我无法在C#中使用“.Union”成功连接两个独立的表,并显示网格中的所有列。有人能告诉我如何解决这个问题吗?
SqlCommand cmd;
SqlCommand cmd1;
SqlCommand cmd2;
string cstr = ConfigurationManager.ConnectionStrings["college"]
.ConnectionString;
using (SqlConnection conn = new SqlConnection(cstr))
{
cmd1 = new SqlCommand("select * from student where studentFirstName LIKE '%'+@studentFirstName+'%'", conn);
cmd1.Parameters.AddWithValue("@studentFirstName", input1);
cmd2 = new SqlCommand("select * from employee where empFirstName LIKE '%'+@empFirstName+'%'", conn);
cmd2.Parameters.AddWithValue("@empFirstName", input2);
cmd = ((cmd1) .Union (cmd2));
}
SqlDataAdapter dAdapt = new SqlDataAdapter(cmd);
DataSet dSet = new DataSet();
dAdapt.Fill(dSet);
答案 0 :(得分:3)
union
没有SqlCommand
方法。但是您可以在一个数据集上多次调用Fill()
方法:
DataSet dSet = new DataSet();
SqlDataAdapter dAdapt1 = new SqlDataAdapter(cmd1);
dAdapt1.Fill(dSet);
SqlDataAdapter dAdapt2 = new SqlDataAdapter(cmd2);
dAdapt2.Fill(dSet);
可能您可能会考虑创建存储过程以在服务器级别执行联合。
有两点需要注意:
Fill()
相当于UNION ALL
(简单UNION
消除了重复项); 答案 1 :(得分:-1)
这两个表都应该在Union i中返回相同数量的具有相同名称的列。如下查询可能有效:
SELECT StudentName As Name FROM Students WHERE StudentName LIKE 'abc%'
UNION
SELECT EmployeeName As Name FROM Employees WHERE EmployeeName LIKE 'abc%'