简体   繁体   中英

How can I create a multi value for a column?

I have two tables TBLCustomers and TBLGroupCustomers . I want to insert multi value in a third table that

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 , CName from TBLCustomers and GName from TBLGroupCustomers

To do this, I created a stored procedure:

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

Because I want show the name of customers join group I want each record of table have a single cname and gname,

C# code

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();
    }
}

It's not working what do I for this?

You need to define the parameters once , before the foreach loop, and then just set their values on each iteration - something like this:

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();
         }
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM