Michelle Carthy

Michelle Carthy

  • NA
  • 52
  • 10.8k

How to use a join in an insert statement and sql server

Nov 2 2017 4:04 PM
So I have two tables, landlords and property.
I am trying to insert data into my property table which works fine however I have to type the landlord id of whoever is logged in at that time in order for it to work. I was wondering is there a way to use an inner join with an insert statement. 
 
I have previously done this using a select statement like so:
 
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["rent-dbConnectionString1"].ToString();
con.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "select p.Property_Id, p.Property_Address, p.Property_Num_Of_Tenants, p.Property_Vacant from Properties p inner join Landlords l On p.Landlord_Id = l.Landlord_Id where l.Landlord_Id = p.Landlord_Id and l.Landlord_Email = '" + checkEmail + "'";
comm.Connection = con;
SqlDataReader rd = comm.ExecuteReader();
 
However, I am unsure how to use it for an insert statement as it is different than a select. This is my insert code at the moment:
 
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["rent-dbConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO Properties(Landlord_Id, Property_Address, Property_Num_Of_Tenants, Property_Vacant) values('" + this.txtLandlordId.Text + "','" + this.txtPropertyAddress.Text + "','" + this.txtNumOfTenants.Text + "','" + this.chkVacant.Checked + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
 
 

Answers (1)