我现在数据库有三个表Phone1,Phone2,Phone3.想利用union把Phone1,Phone2的数据插入到第三个表中。 我用的是sql sever。
求各位大神给段实例代码,不要仅仅给个sql语句,小弟刚刚自学C#,对C#操纵数据库还不是很熟悉,求完整代码。感激不尽啊。
string sql = "insert into phone3 (select * from phone1 union select * from phone2)";
ado.net:
SqlConnection con = new SqlConnection("...");
SqlCommand cmd = new SqlCommand(sql,con);
int rows = cmd.ExecuteNonQuery();
if(rows > 0)
{
//成功
}
前提是phone1、phone2、phone3三张表的表结构一样。
private void Form3_Load(object sender, EventArgs e)
{
string sql = "insert into Phone3 (select * from Phone1 union select * from Phone2)";
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(sql,con);
int rows = cmd.ExecuteNonQuery();
/*SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "insert into Phone3 (select * from Phone1 union select * from Phone2)";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();*/
还是没有插入成功。写在代码里是这样的,注释掉的是我原来写的。求前辈在帮忙看一下
好想少个 as......,或者说 phone3 的表结构 跟你查询出的表结构不相同......
额。。是create table as吧。而且三个表的结构完全一样。