0

In the database I created a stored procedure

ALTER procedure [dbo].[usercusdet_pro](@user varchar(25),@cusname varchar(max))--,@cnt int)
as
begin
    --declare @count int
    --set @count=0
    --if(@count<@cnt)
    insert usercusdet values(@user,@cusname)
end

to insert values. When I click the button, multiple rows should be inserted in the table.

int cnt = gvTranferRows.Rows.Count;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gdb"].ConnectionString);

con.Open();

SqlCommand cmd = new SqlCommand("usercusdet_pro", con);
cmd.CommandType = CommandType.StoredProcedure;

if (con.State == ConnectionState.Closed)
    con.Open();

for (int i=0;i<cnt;i++)
{
     cmd.Parameters.Add("@user", SqlDbType.VarChar).Value = "A001";
     cmd.Parameters.AddWithValue("@cusname",gvTranferRows.Rows[i].Cells[0].Text);
     //cmd.Parameters.AddWithValue("@cnt", cnt);
     cmd.ExecuteNonQuery();
}

When I try to add value it shows an error:

procedure or function has too many arguments specified

What's the cause of this error?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gopi
  • 140
  • 2
  • 8
  • 17

2 Answers2

0

You need to clear the parameters before the next iteration i.e.

cmd.Parameters.Add("@user", SqlDbType.VarChar).Value = "A001";
cmd.Parameters.AddWithValue("@cusname",gvTranferRows.Rows[i].Cells[0].Text);
//cmd.Parameters.AddWithValue("@cnt", cnt);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();

Or given the @user parameter is fixed, you just need to replace the @cusname one

cmd.Parameters.Add("@user", SqlDbType.VarChar).Value = "A001";
for (int i=0;i<cnt;i++)
{
    cmd.Parameters.AddWithValue("@cusname",gvTranferRows.Rows[i].Cells[0].Text);
    cmd.ExecuteNonQuery();
    cmd.Parameters.RemoveAt("@cusname");
}
James
  • 80,725
  • 18
  • 167
  • 237
  • hai james it worked.thanks.one more doubt where insert into table it stored in the random order. it is not inserting one by one like as ususal – Gopi Sep 18 '13 at 12:01
0

You can use Table valued parameter starting sql server 2008 onwards.

OR

Youc an go for passing data as XML if using version prior to SQL Server 2008.

OR

Not a good apporach but you can use delimiter seperated string as well.

Community
  • 1
  • 1
Shantanu Gupta
  • 20,688
  • 54
  • 182
  • 286