Invoke function with stored procedure as parameter - c#

I have the following function in C# which is working fine
private void AddQueue()
{
SqlConnection conn = forconnection();
conn.Open();
SqlCommand cmd = new SqlCommand("spInsertFormIssue",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Qdatetime", SqlDbType.DateTime).Value = DateTime.Now;
cmd.ExecuteNonQuery();
conn.Close();
}
Now I want the same function but with different stored procedure, I want to reuse this function with another stored procedure.
How do I pass stored procedure as argument?

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

Just pass name of the stored procedure as parameter:
string procedureName = "spInsertFormIssue";
private void AddQueue(string procedureName)
{
SqlConnection conn = forconnection();
conn.Open();
SqlCommand cmd = new SqlCommand(procedureName,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Qdatetime", SqlDbType.DateTime).Value = DateTime.Now;
cmd.ExecuteNonQuery();
conn.Close();
}

Related

I want to pass a list of SqlParameter to a function which executes stored procedure in C#

I want to save two values say #name and #pwd to a table, for this I can use following code in aspx page.
public void save1()
{
try
{
using (SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString))
{
using(SqlCommand cmd = new SqlCommand("SP_TEST",con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#name", txtUname.Text);
cmd.Parameters.Add("#pwd", txtPwd.Text);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{ }
}
But I want to pass these two variable as a single List<SqlParameter> variable as
List<SqlParameter> param = new List<SqlParameter>();
param.Add(new SqlParameter("#name", uname));
param.Add(new SqlParameter("#pwd", pwd));
Thus the declaration of above function changes from
public void save1()
to
public void save1(List<SqlParameter> param)
But my problem is I don't know how to extract those two variables from this param and then add them to the cmd variable. I need your help.
Have your Save function look like so:
public void Save1(List<SqlParameter> param)
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager
.ConnectionStrings["myCon"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SP_TEST", con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var item in param)
cmd.Parameters.Add(item);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
/*...*/
}
}
Then have param be accessible to the calling routine as well as the Save1(..) function, like so:
public/*private*/ List<SqlParameter> param = new List<SqlParameter>();
Lastly, your calling routine will call Save1(..) as following:
string uname = "...";
string pwd = "...";
param.Add(new SqlParameter("#name", uname));
param.Add(new SqlParameter("#pwd", pwd));
Save1(param);
If you know there's only going to be two parameters you could use this
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(param[0]);
cmd.Parameters.Add(param[1]);
cmd.ExecuteNonQuery();
See below code
List<SqlParameter> Parameters = new List<SqlParameter>(){
new SqlParameter() {ParameterName = "#yourparamname", SqlDbType = SqlDbType.NVarChar, Value= ""}
,..
};
public void ExecuteSQL(string SP, List<SqlParameter> Parameters){
SqlConnection CN = new SqlConnection("ConnectionString");SqlCommand CM = new SqlCommand(SP, CN);CM.CommandType = CommandType.StoredProcedure;
CM.Parameters.AddRange(Parameters.ToArray());CM.ExecuteNonQuery();CM.Conection.Dispose();
}
ExecuteSQL("dbo.[SP_Name]", Parameters);
The key is: CM.Parameters.AddRange(Parameters.ToArray());
You can use a for loop to access each individual parameter inside the list.
for(interesting i=0, i< parameter.Count, i++){
//
var param1 = param[i];
}

Detect if stored proc delete ran

If I calling a stored proc how do i detect that it has completed succesfully on the server as right now im just doing a try catch which is not the best way of doing this.
public bool deleteTeam(Guid teamId)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["uniteCms"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cs.ToString());
// the stored procedure
SqlCommand cmd = new SqlCommand(
"proc_unitecms_deleteTeam", myConnection);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#ID", teamId));
return true;
} catch(Exception ex)
{
return false;
}
}
You can return the affected rows number and return -1 in case of catch a exception .
You forget the ExecuteNonQuery.
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
Int32 rowsAffected;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();

Calling a Stored procedure

I'm new to C# I need to call a SP and return the table value from C#.
I'm passing current datetime(#currentdate) as my input parameter in the stored procedure.So how do I pass this in C# method?
Pls help me to write a C# method to call that SP and return the value
I have my sp ready. sp will return the top updated record in the table.
I have used this in my C# code
string _Num = null;
SqlConnection sqlConnection1 = new SqlConnection("Data Source=localhost;Initial Catalog=ReferenceDB;Persist Security Info=True;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand();
Int32 rowsAffected;
Object returnValue;
cmd.CommandText = "Number";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CurrentDate", DateTime.Now);
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
returnValue = cmd.ExecuteScalar();
if (returnValue != null)
_Num = returnValue.ToString();
return _Num
Write his code in that method
SqlConnection con = new SqlConnection("coonectionstring");
SqlCommand cmd = new SqlCommand();
SqlCommand cmd = new SqlCommand("Your sp",con);
cmd.CommandType = CommandType.StoredProcedure;
//input parameters
cmd.Parameters.Add(new SqlParameter("#currentdate",SqlDbType.DateTime,"currentdate"));
int i=command.ExecuteNonQuery();
If you are going to use more than one sp in your C# code, I suggest something like this:
public static DataTable GetSQLValues(string currentDate)
{
SqlParameter[] sqlParams =
{
new SqlParameter("#currentDate", currentDate)
};
return DBHelper.GetTable("MSSQLSPNAME", sqlParams);
}
Use the above for every instance where you need to get table info.
GetTable looks like this:
static SqlConnection _conn;
static string _connStr = ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["primaryConnStr"]].ToString();
static SqlCommand _cmd;
static SqlDataAdapter _dataAdapter = new SqlDataAdapter();
public static DataTable GetTable(string sProcName, SqlParameter[] sqlParams)
{
using (_conn = new SqlConnection(_connStr))
{
_cmd = new SqlCommand(sProcName, _conn);
_conn.Open();
_cmd.CommandType = CommandType.StoredProcedure;
if (sqlParams != null)
{
_cmd.Parameters.AddRange(sqlParams);
}
_dataAdapter = new SqlDataAdapter(_cmd);
var results = new DataTable();
_dataAdapter.Fill(results);
_conn.Close();
return results;
}
}
It will save you a ton of time for each sp call you need from C#.

code help for stored procedure dll class

i m making dll class for stored procedure as...help me to correct it...my boss said that i m missing parameter values to return but i m not getting anything to correct it...
public class transactionService
{
SqlConnection cs;
private void OpenConnection()
{
cs = new SqlConnection();
cs.ConnectionString = "Data Source=IRIS-CSG-174;Initial Catalog=library_system;Integrated Security=True";
cs.Open();
}
public membership_details calculatefine()
{
OpenConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Exec member_fine_detail";
cmd.Parameters.Add(new SqlParameter("member_id", SqlDbType.Int));
membership_details myObjec = new membership_details();
cmd.ExecuteNonQuery();
SqlDataReader sdr = cmd.ExecuteReader();
myObjec.fine_per_day = 0;
return myObjec;
help me to correct this code...i m trying to get fne_per_day as per member_id and after this reference is adding to return form in project from that according to member_id fine_per_day is calculated...as the creteria is like member_id=5,membership_desc=silver,gol,platinum,fineperday=30or 20or10
I think you will need something like this for returning the out parameter of your stored procedure:
public membership_details calculatefine()
{
OpenConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Exec member_fine_detail";
cmd.Parameters.Add(new SqlParameter("#member_id", SqlDbType.Int));
//Sql parameter corresponding to the output parameter
cmd.Parameters.Add(new SqlParameter("#fine_per_day", SqlDbType.Int));
cmd.Parameters[cmd.Parameters.Count - 1].Direction = ParameterDirection.Output;
//execute the stored procedure
cmd.ExecuteNonQuery();
//obtain the value for the output parameter
myObjec.fine_per_day = (int)cmd.Parameters["#fine_per_day"].Value;
return myObjec;
}

How to call a mySQL stored function in C#?

I'd like to call a stored function in C#. I need articles and some examples for this.
It's almost identical to how you would call a SQL Server Stored Procedure:
using(MySqlConnection conn = new MySqlConnection(connString))
{
MySqlCommand command = new MySqlCommand("spSomeProcedure;", conn);
command.CommandType = System.Data.CommandType.StoredProcedure;
// Add your parameters here if you need them
command.Parameters.Add(new MySqlParameter("someParam", someParamValue));
conn.Open();
int result = (int)command.ExecuteScalar();
}
http://forums.asp.net/p/988462/1278686.aspx
MySqlCommand cmd = new MySqlCommand("DeleteMessage", new MySqlConnection(GetConnectionString()));
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new MySqlParameter("param1", MessageItem.Entry_ID));
cmd.Connection.Open();
int i = cmd.ExecuteNonQuery();
cmd.Connection.Close();
Stored routines
Stored functions and stored procedures are called in different ways.
Stored function is used as regular function in SQL statement.
For example
SELECT id, title, my_function(price) FROM table
Stored procedures are called using CALL statement.
CALL my_procedure(1,2,'title');
I don't know C#, so probably you can use MySqlCommand class to call stored procedures, but you can't use it to call stored functions.
I actually couldn't get the other methods suggested to return a value. I ended up creating a string to call the function and then executed that string with .ExecuteScalar:
MySqlTransaction mySqlTransaction = testDataMySqlConnection.BeginTransaction();
mySqlCommand = new MySqlCommand
{
Connection = testDataMySqlConnection,
CommandText = "SELECT sf_UnitsAttempted('" + ... + ");",
CommandType = CommandType.Text
};
var f = (float)mySqlCommand.ExecuteScalar();
mySqlCommand.Dispose();
return f;
I know the question is about returning from a stored function, and Justin's answer here covers that. I wanted to add that if you wanted to return a DataTable from a stored procedure instead, you can do it using a DataAdapter:
// using MySql.Data.MySqlClient; // remember to include this
/* Helper method that takes in a Dictionary list of parameters,
and returns a DataTable.
The connection string is fetched from a resources file. */
public static DataTable ExecuteProc(string procedureName, Dictionary<string,object> parameterList)
{
DataTable outputDataTable;
using (MySqlConnection MySqlConnection = new MySqlConnection(Resources.SQL_CONNECTION_STRING))
{
using (MySqlCommand sqlCommand = new MySqlCommand(procedureName, MySqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
if (parameterList != null)
{
foreach(string key in parameterList.Keys)
{
string parameterName = key;
object parameterValue = parameterList[key];
sqlCommand.Parameters.Add(new MySqlParameter(parameterName, parameterValue));
}
}
MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(sqlCommand);
DataSet outputDataSet = new DataSet();
sqlDataAdapter.Fill(outputDataSet, "resultset");
outputDataTable = outputDataSet.Tables["resultset"];
}
}
return outputDataTable;
}

Categories