更新一个表并插入SQL Server 2008中的另一个表

时间:2014-10-09 09:05:46

标签: c# sql-server-2008 merge insert-update

我有两个表公司,其中包含CompanyID {auto increment primary key}和group with GroupID {auto increment primary key}。在组表中,我想在提交按钮单击时插入组详细信息,同时使用刚刚插入组表中的GroupID更新公司表的组列。请建议我如何使用单独的命令或通过存储过程执行此操作。我对SQL服务器查询有点弱,所以需要一些帮助解释。我做错了什么,它给出了“关键字'内部'附近的语法不正确”。提前谢谢。

Company table

Group table

Submit button on web form

提交按钮点击代码:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    string group = GroupName.Text;
    string dept = Department.Text;
    string company = Session["com"].ToString();

    if ((HttpContext.Current.User != null) && HttpContext.Current.User.Identity.IsAuthenticated && company != null)
    {
        string strcon = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
        SqlConnection con = new SqlConnection(strcon);
        con.Open();
        DataSet ds = new DataSet();
        SqlDataReader rdr = null;
        SqlCommand cmd1 = new SqlCommand("Insert into Group(GroupName, Department, CompanyID) Values(@groupName, @department, 'Select CompanyID from Company1 where Company.CompanyName=@companyName')", con);
        SqlCommand cmd = new SqlCommand("Update Company1 set Company1.Groups=Group.GroupID inner join Group on Group.CompanyID=Comapny1.CompanyID"
                        +" where Company.CompanyName=@companyName", con);
        cmd1.Parameters.Add("@groupName", SqlDbType.NVarChar).Value = group;
        cmd1.Parameters.Add("@department", SqlDbType.NVarChar).Value = dept;
        cmd1.Parameters.Add("@companyName", SqlDbType.NVarChar).Value = company;
        cmd.Parameters.Add("@companyName", SqlDbType.NVarChar).Value = company;
        //cmd1.Parameters.AddWithValue("@groupName", group);
        //cmd1.Parameters.AddWithValue("@department", dept);
        //cmd.Parameters.AddWithValue("@companyName", company);

        rdr = cmd1.ExecuteReader();
        rdr = cmd.ExecuteReader();
        con.Close();
    }
    else
    {
        Response.Redirect("Account/Login.aspx");
    }
}

1 个答案:

答案 0 :(得分:1)

参考此评论:

  

公司中的GroupID被视为NVARCHAR(30),以便用逗号分隔多个GroupID,我怎么能实现这个想法呢?

答案是不要的。您正在复制数据,存储关系作为分隔字符串从不在关系数据库中是个好主意。它违背了目的。

我认为您需要做的就是在插入群组的同时插入CompanyID

INSERT dbo.Group (GroupName, Department, CustomerID)
SELECT  @GroupName, @Department, c.CompanyID
FROM    dbo.Company1 AS c
WHERE   c.CustomerName = @CustomerName;

所以你的c#最终看起来像:

string sql = @"INSERT dbo.[Group] (GroupName, Department, CustomerID)
                SELECT  @GroupName, @Department, c.CompanyID
                FROM    dbo.Company1 AS c
                WHERE   c.CompanyName = @CompanyName;";
string strcon = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;

using (var connection = new SqlConnection(strcon))
using (var command = new SqlCommand(sql, connection))
{
    connection.Open();
    command.Parameters.Add(@GroupName, SqlDbType.NVarChar, 50).Value = group;
    command.Parameters.Add(@Department, SqlDbType.NVarChar, 50).Value = dept;
    command.Parameters.Add(@CompanyName, SqlDbType.NVarChar, 50).Value = company;
    command.ExecuteNonQuery();
}

请注意使用ExecuteNonQuery()代替ExecuteReader(),因为您实际上并未阅读任何内容,并且使用using块来确保正确处理对象。我还在您的查询中包含了架构前缀(假设为dbo),因为它是usually a good idea to include this as standard

如果您需要获取与特定公司相关联的组,请在查询中执行此操作,以避免每Groups次重新计算INSERT/UPDATE/DELETE列:

SELECT  c.CompanyID,
        c.CompanyName,
        Groups = STUFF((SELECT ',' + CAST(g.GroupID AS VARCHAR(10))
                        FROM    dbo.[Group] AS g
                        WHERE   g.CompanyID = c.CompanyID
                        FOR XML PATH(''), TYPE
                        ).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM    dbo.Company AS c;

有关将行连接到列的详细信息,请参阅this answer;