winforms 将逗号分隔的列表作为单独的行添加到SQL Server

2exbekwf  于 2022-11-17  发布在  SQL Server
关注(0)|答案(1)|浏览(181)

我还不是最擅长使用SQL,但我正在尝试获得一个逗号分隔的列表,以转换成我的数据库中的多行。例如,我正在使用Winforms,在我的文本框中我将输入“a,b,c”
我希望我的表如下所示:

但到目前为止,我只取得了:

下面是一些示例代码:

private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                listBox1.SetSelected(i, true);
            }
            string items = "";
            StringBuilder sb = new StringBuilder();
            foreach (var currentItem in listBox1.SelectedItems)
            {
                sb.Append(currentItem + ",");
                          
            }
            items = sb.ToString();

            textBox1.Text = items;
        }

SQL语言

string strsql;        
strsql = @"UPDATE [table].[dbo].[Departments]
           SET [dep_Department] = @department                           
           WHERE [dep_Username] = @username;

           IF @@ROWCOUNT = 0
               INSERT INTO [table].[dbo].[Departments] ([dep_Username],[dep_Department]) 
               VALUES (@username, @department);";

SqlConnection conn = new SqlConnection(@"coneectionstring;");
var cmd = new SqlCommand(strsql, conn);  

cmd.Parameters.Add("@department", SqlDbType.NVarChar, 40).Value = department;
cmd.Parameters.Add("@username", SqlDbType.NVarChar, 60).Value = username;          

conn.Open();
cmd.ExecuteNonQuery();
pbossiut

pbossiut1#

您只需要拆分 departmentname 变量以提取单个部门,然后循环提取的部门。
但首先,如果需要为每个部门/用户对写入一条记录,则需要删除该用户的所有记录,然后重新写入它们。所有这些都在事务中完成。当然,我假定 departmentname 包含要为特定用户添加的所有部门。
所以我们有两个sql命令文本,第一个删除记录,第二个添加记录。SqlCommand和它的第一个参数立即生成,命令用于删除记录,然后我们可以更改命令文本,并在循环外部添加部门名称参数,在循环内部,您可以用当前值更新 @department 参数。

try
{
    string clear_recs = @"DELETE FROM [Departments] 
                          WHERE [dep_Username] = @username";

    string strsql = @"INSERT INTO [table].[dbo].[Departments]  
                     ([dep_Username],[dep_Department]) 
                      VALUES (@username, @department);";
    
    using(SqlConnection conn = new SqlConnection(@"coneectionstring;"));
    conn.Open();
    using(SqlTransaction tr = conn.BeginTransaction());
    using(SqlCommand cmd = new SqlCommand(clear_recs, conn, tr));  
    cmd.Parameters.Add("@username", SqlDbType.NVarChar, 60).Value = username;
    cmd.ExecuteNonQuery();
    // Change the commandtext and create the parameter 
    // but do not set the value for now.
    cmd.CommandText = strsql;
    cmd.Parameters.Add("@department", SqlDbType.NVarChar, 40);

    // Split, then loop and update/insert 
    // using the same SqlCommand.
    string[] deps = department.Split(',');
    foreach(string dep in deps)
    {
        cmd.Paramenters["@department"].Value = dep;
        cmd.ExecuteNonQuery();
    }
    // All the write are effectively done here when we commit the transaction
    tr.Commit();
}
catch(Exception ex)
{
    // Log the errors. If we reach the exception handler, the  
    // transaction is automatically rolled back and you can try again.
}

相关问题