如何为列创建多值?

时间:2016-02-07 08:21:57

标签: c# sql-server insert

我有两张表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)
)
来自CEmail的{​​p> CNameTBLCustomers和来自GName的{​​{1}}

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

TBLGroupCustomers

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

C#代码

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

这不起作用我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要在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();
         }
     }
}