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?

2 Answers 2

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.