如何为列创建多值

本文关键字:创建 | 更新日期: 2023-09-27 18:33:42

我有两个表TBLCustomersTBLGroupCustomers。我想在第三个表中插入多值

CREATE TABLE [dbo].[TBLG_Groups] 
(
    [GrId]   INT           IDENTITY (1, 1) NOT NULL,
    [CEmail] VARCHAR (250) NOT NULL,
    [GName]  NVARCHAR (70) NOT NULL,
    [CName]  NVARCHAR (450) NULL, 
    PRIMARY KEY CLUSTERED ([GrId] ASC, [CEmail] ASC, [GName] ASC)
)

CEmailCName来自TBLCustomersGName来自TBLGroupCustomers

为此,我创建了一个存储过程:

CREATE PROC dbo.spG_Groups
    @CEmail VARCHAR(250),
    @GName NVARCHAR (70),
    @CName NVARCHAR(450)
AS
BEGIN
    INSERT INTO TBLG_Groups(CEmail, GName, CName)
    VALUES (@CEmail, @GName, @CName)
END

因为我想显示客户加入组的名称,所以我希望表的每个记录都有一个 cname 和 gname,

C# 代码

SqlCommand cmd1 = new SqlCommand("spG_Groups", conn);
cmd1.CommandType = CommandType.StoredProcedure;
List<String> YrStrList1 = new List<string>(); 
foreach (ListItem li in chGp.Items)
{
    if (li.Selected)
    {
        YrStrList1.Add(li.Value);
        cmd1.Parameters.Add(new SqlParameter("@CName", txtCName.Value));
        cmd1.Parameters.Add(new SqlParameter("@CEmail", txtemail.Value));
        cmd1.Parameters.Add(new SqlParameter("@GName", YrStrList1.ToString()));
        cmd1.ExecuteNonQuery();
    }
}

它不起作用,我该怎么办?

如何为列创建多值

您需要在

foreach循环之前定义一次参数,然后在每次迭代中设置它们的值 - 如下所示:

using (SqlCommand cmd1 = new SqlCommand("spG_Groups", conn))
{
     cmd1.CommandType = CommandType.StoredProcedure;
     // define the parameters *ONCE*
     cmd1.Parameters.Add("@CName", SqlDbType.NVarChar, 450);
     cmd1.Parameters.Add("@CEmail", SqlDbType.VarChar, 250);
     cmd1.Parameters.Add("@GName", SqlDbType.NVarChar, 70);
     List<String> YrStrList1 = new List<string>(); 
     foreach (ListItem li in chGp.Items)
     {
         if (li.Selected)
         {
              YrStrList1.Add(li.Value);
              // just set the *VALUES* of the parameters
              cmd1.Parameters["@CName"].Value = txtCName.Value;
              cmd1.Parameters["@CEmail"].Value = txtemail.Value;
              cmd1.Parameters["@GName"].Value = YrStrList1.ToString();
              cmd1.ExecuteNonQuery();
         }
     }
}