日期:2014-05-20  浏览次数:21021 次

如何用SqlCommand执行连接查询。
string constr = @"data source=.\sqlexpress;initial catalog = HR;user id =sa;password=123456";
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = constr;
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    string query = "select b.cEmployeeCode,b.vFirstName,b.vAddress, a.vDepartmentName";
                    query += " from dbo.Department a join dbo.Employee b";
                    query += " on a.cDepartmentCode = b.cDepartmentCode ";
                    query += "where a.vDepartmentName ='@Sales'";
                    cmd.CommandText = query;
                    SqlParameter sql = new SqlParameter("@Sales", SqlDbType.VarChar,25);  ///
                    sql.Value = this.textBox1.Text.Trim();
                    cmd.Parameters.Add(sql);
                    cmd.CommandType = CommandType.Text;   ////
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        string address = dr.GetString(dr.GetOrdinal("a.vDepartmentName"));
                        MessageBox.Show("地址是:" + address);
                        this.textBox2.Text = address;
                    }
                    dr.Close();
                }
            }
        }

可以提供代码参考吗:有请发送至:124539132@qq.com
sql 多表查询

------解决方案--------------------
string constr = @"data source=.\sqlexpress;initial catalog = HR;user id =sa;password=123456";
using (SqlConnection conn = new SqlConnection())
{
    conn.ConnectionString = constr;
    conn.Open();
    using (SqlCommand cmd = conn.CreateCommand())
    {
        string query = "select b.cEmployeeCode,b.vFirstName,b.vAddress, a.vDepartmentName";
        query += " from dbo.Department a join dbo.Employee b";
        query += " on a.cDepartmentCode = b.cDepartmentCode ";
        query += "where a.vDepartmentName ='@Sales'";
        cmd.CommandText = query;