Call a Stored Procedure With Parameter in C#

Call a stored procedure with parameter in c#

It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.

Also, use a using for all disposable objects, so that you are sure that they are disposed properly:

private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

con.Open();
cmd.ExecuteNonQuery();
}
}
}

Call SQL Server stored procedure with parameters using C#

Hmmm looks like you are not telling the command object that it is a stored procedure not a regular query try this one

    sqcon.Open();
SqlCommand cmd = new SqlCommand("Users.PR_Authenticate_WebUsers",sqcon);
cmd.CommandType = CommandType.StoredProcedure;

//Add parameters like this
cmd.Parameters.Add(new SqlParameter("@In_UserID", "f"));
sqcon.Close()

C# : how to use parameters for SQL Server stored procedure?


SqlCommand command = new SqlCommand("SP_GetCityByID ", conn);

You don't put a where condition when you call a stored procedure. where condition needs to be inside the body of stored procedure which should compare the id column of your city table with @ID parameter you are passing to stored procedure. Secondly, ExecuteNonQuery function which you have written at the end will not serve your purpose. Use ExecuteScalar function instead as given below:

String cityName= command.ExecuteScalar();

I am assuming your stored procedure accepts parameter @ID and returns matching city name in the form of table.

Invoke function with stored procedure as parameter

You can get the stored procedure name and parameters from request argument.

Like this:

private void AddQueue(string spName, List<SqlParameter> SqlParameters)
{
...
SqlCommand cmd = new SqlCommand(spName, conn);
...

if (SqlParameters.Count > 0)
cmd.Parameters.AddRange(SqlParameters.ToArray());

...
}

And you can call it like this:

List<SqlParameter> sqlParameters = new List<SqlParameter>();
sqlParameters.Add(new SqlParameter("@Qdatetime", SqlDbType.DateTime) { Value = DateTime.Now });

AddQueue("spInsertFormIssue", sqlParameters);

C# stored procedure with parameters

My guess is that in

   myCommand2.Parameters.Add("@TaskName", SqlDbType.NVarChar, 50).Value = t;

t is not a string?



Related Topics



Leave a reply



Submit