【问题标题】:How to use a join in an insert statement and sql server C# Asp.net如何在插入语句和 sql server C# Asp.net 中使用连接
【发布时间】: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


【解决方案1】:

我假设您正在做一个 Web 表单应用程序,并且您的系统有一个登录名,因为有多个房东更新一个属性。

注意事项和最佳实践:

1) 由于您有登录名,因此在 ASP.Net 中有一个名为 Sessions 的全局变量,您可以保存登录用户的 ID 或任何您必须保存的重要详细信息。你可以这样做:

Session["landlordId"] = landlord.Id; //landlord is a class and
                                     //Id is the property inside the class

2) 使用会话无论您在哪个页面,您都可以通过以下方式访问它:

string loggedUser = (string)(Session["landlordId"]);
                    //Session["landlordId"].ToString(); or like this

3) 为了安全起见,始终使用参数化查询(以避免 SQL 注入)例如:

SqlCommand cmd = new SqlCommand("INSERT INTO Properties(Landlord_Id, 
Property_Address, Property_Num_Of_Tenants, Property_Vacant) values(@landlordID, @propertyAddress, @propertyNumOfTenants, @propertyVacant)", con);
cmd.Parameters.Add("@landlordID", sqlDbType.Int32).Value = Session["landlordId"].ToString();
//and do the same for other parameters
con.Open();
cmd.ExecuteNonQuery();
con.Close();

如果您遵循第 1 步和第 2 步,您的问题将不再困难。您可以像第 3 步一样进行插入操作。无需连接或复杂代码,只需插入单个表即可。

【讨论】:

    【解决方案2】:

    这是基于主键和外键引用将数据插入两个表的存储过程。

    首先创建过程

    CREATE PROCEDURE spName AS
    GO
    

    现在改变程序

    ALTER PROCEDURE [dbo].[spName] AS
    BEGIN
     SET NOCOUNT ON;
     SET XACT_ABORT ON;
      insert into Table1(Col1, Col2) values (val1,val2) -- put other values here (from parameters?)
       insert into Table2(Table1primaryKey, col2, col3) values (SCOPE_IDENTITY(), val2, val3) --Scope_Identity() method will get last inserted primary key of first Table and put other values here (from parameters?) instead of Val1,val2 etc.
       
    SET NOCOUNT OFF;
        SET XACT_ABORT OFF;
        END
    

    我希望这能解决您的问题,因为它对我有用!

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 2012-03-19
      相关资源
      最近更新 更多