【发布时间】:2018-04-15 13:39:25
【问题描述】:
所以我有两张桌子,房东和财产。 我正在尝试将数据插入到我的属性表中,该表工作正常,但是我必须输入当时登录的任何人的房东 ID 才能使其正常工作。我想知道有没有办法使用带有插入语句的内部连接。
我之前使用过这样的 select 语句来完成此操作,它向我显示了与已登录的房东相关的所有属性:
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();
但是,我不确定如何将它用于插入语句,因为它与选择不同。这是我此刻的插入代码:
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();
【问题讨论】:
-
在 INSERT 语句中使用 SELECT 的基本查询形式是相同的 - 您只需从 INSERT 语句开始,例如
INSERT INTO MyTable (Field1, Field2, Field3) SELECT IDField, '" + this.Field2Data + "', '" + this.Field3Data + "' FROM MyTable WHERE Fieldx = '" + this.LookupData + "'" -
通常你会选择id然后单独插入。存储过程可以很方便地做到这一点,因为您对数据库上的一个过程进行一次调用,它将执行选择和插入,而不是对数据库进行两次单独的调用。在不清理输入的情况下执行这样的行内命令是非常糟糕的做法。
标签: c# sql asp.net sql-server join