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();
Related
I need to know why I am still getting this error
Stored procedure expects parameter which was not supplied
But I am actually sending this parameter.
The stored procedure in the database looks like this:
CREATE PROCEDURE SVC_BUSCA_MEDIO_LANDING
(#rut VARCHAR)
AS
BEGIN
SELECT utm_source
FROM landing_formulario
WHERE rut = #rut
END
And my .net code:
string result = string.Empty;
string connString = System.Configuration.ConfigurationManager.AppSettings["StPazWeb"].ToString();
string SVC_BUSCA_MEDIO_LANDING = "SVC_BUSCA_MEDIO_LANDING";
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
try
{
SqlCommand command = new SqlCommand(SVC_BUSCA_MEDIO_LANDING);
command.CommandType = CommandType.StoredProcedure;
command = new SqlCommand(command.CommandText, connection);
command.Parameters.AddWithValue("#rut", rut);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
result = (string)reader["utm_source"];
}
}
catch (SqlException ex)
{
throw new Exception("Oops!." + ex.Message);
}
}
return result.ToString();
Any idea what can be happening?
For some reason you create the command twice, with the second instantiation replacing the first, however on the second one you don't set the command type, and as a result your parameter is being ignored.
Try:
SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = SVC_BUSCA_MEDIO_LANDING;
command.Parameters.AddWithValue("#rut", rut);
You're using:
SqlCommand command = new SqlCommand(SVC_BUSCA_MEDIO_LANDING);
but you're reseting the command at:
command = new SqlCommand(command.CommandText, connection);
Try instead:
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SVC_BUSCA_MEDIO_LANDING";
command = new SqlCommand(command.CommandText, connection);
command.Parameters.AddWithValue("#rut", rut);
I have an update statement that works fine when I run it from SQL Developer. However, when I try to run it in C#, the program will freeze on the line that executes the command and not output anything. I have it defined as follows below:
private static OracleCommand cmd = new OracleCommand();
private static OracleConnection conn = new OracleConnection();
conn.ConnectionString = Properties.Settings.Default.myconstring;
cmd.Connection = conn;
cmd.CommandText = "UPDATE mytable SET PARAM1 = :param1 WHERE PARAM2 = :param2";
cmd.CommandType = CommandType.Text;
cmd.BindByName = true;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":param1", OracleDbType.Single)).Value = param1Val;
cmd.Parameters.Add(new OracleParameter(":param2", OracleDbType.Int32)).Value = param2Val;
conn.Open();
try {
cmd.ExecuteNonQuery(); //Freezes here
} catch(Exception e) {
MessageBox.Show(e.ToString());
}
conn.Close();
I have verified my values being put in are correct.
Hi guys I'm having troubles trying execute Stored procedures on cascade, I need some help. Let's see the scenario:
I have a father table, let's call it "REQUEST" and a child table, "REQUEST_DETAILS"
Now from C# I know how to execute an Oracle SP, but I donĀ“t know how to execute two in a chain, without commit until the end of all.
I need to insert the father table data and after get the generated REQUEST.ID to start to insert the children data with the REQUEST.ID
So the first stored procedure will insert the REQUEST data and the second one will insertrt the REQUEST_DETAIL data but if something goes wrong I want to rollback all the transactions.
There is a way to do this of a simple way ?
Here is my code any help will be usefull.
public Bool SaveRequest(Request newRequestData)
{
var connection = new connection();
bool isSuccess = true;
OracleConnection Conn = connection._GetInstance();
OracleCommand Cmd = new OracleCommand();
Conn.Open();
Cmd.Connection = Conn;
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.CommandText = "PackageRequests.InsertNewRequest";
Cmd.BindByName = true;
//IN PARAM
Cmd.Parameters.Add(new OracleParameter("P_LOCATION", OracleDbType.Varchar2, newRequestData.location, ParameterDirection.Input));
Cmd.Parameters.Add(new OracleParameter("P_PCSTOTAL", OracleDbType.Int32, newRequestData.pcsTotal, ParameterDirection.Input));
Cmd.Parameters.Add(new OracleParameter("P_STATUS", OracleDbType.Int32, newRequestData.status, ParameterDirection.Input));
//Out Param
Cmd.Parameters.Add(new OracleParameter("P_NEW_ID", OracleDbType.Int32)).Direction = ParameterDirection.Output;
OracleTransaction transaction = Conn.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
Cmd.ExecuteNonQuery();
//New request_id
string newId = Convert.ToString(Cmd.Parameters["P_NEW_ID"].Value);
//Here I think goes the logic for execute the another procedure that will insert the data into REQUEST_DETAIL
/***
foreach(var item in newRequestData.List)
{
//Insert request_detail_Data()
}
***/
//after all -- transaction.Commit();
}
catch (OracleException ex)
{
//If something goes wrong rollback.
transaction.Rollback();
isSuccess = false;
}
finally
{
Conn.Close();
}
return isSuccess;
}
I found the solution to do this the trick is on pass the Oracle Connection like parameter to the another functions and when all is done commit and if something fails rollback, from the initial function. I leave an example I hope will be helpful for someone.
public Bool SaveRequest(Request newRequestData)
{
var connection = new connection();
bool isSuccess = true;
OracleConnection Conn = connection._GetInstance();
OracleCommand Cmd = new OracleCommand();
Conn.Open();
Cmd.Connection = Conn;
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.CommandText = "PackageRequests.InsertNewRequest";
Cmd.BindByName = true;
// IN PARAMETERS...
Cmd.Parameters.Add(new OracleParameter("P_LOCATION", OracleDbType.Varchar2, newRequestData.location, ParameterDirection.Input));
// OUT PARAMETER (Here I recover the master table ID)
Cmd.Parameters.Add(new OracleParameter("P_NEW_ID", OracleDbType.Int32)).Direction = ParameterDirection.Output;
// Initialize the Transaction
OracleTransaction transaction = Conn.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
//Execute the first SP
Cmd.ExecuteNonQuery();
string newId = Convert.ToString(Cmd.Parameters["P_NEW_ID"].Value);
// Calls another function and pass Oracle Connection, and master table ID like parameters
InsertRequestDetail(Conn, newId);
transaction.Commit();
}
catch (OracleException ex)
{
//If something goes wrong rollback.
transaction.Rollback();
isSuccess = false;
}
finally
{
Conn.Close();
}
return isSuccess;
}
private void InsertRequestDetail(OracleConnection Conn, string newId)
{
OracleCommand Cmd = new OracleCommand();
Cmd.Connection = Conn;
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.CommandText = "MY_PACKAGE.AnotherSPName";
Cmd.BindByName = true;
//IN - OUT PARAMS
Cmd.Parameters.Add(new OracleParameter("...
Cmd.ExecuteNonQuery();
}
My code shown below is create as an inline SQL statement. How can this code be written as a stored procedure??
The code is:
public Stream SelectEmployeeImageByID(int theID)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString());
string sql = "SELECT Image FROM Employees WHERE EmployeeId = #EmployeeId";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeId", theID);
connection.Open();
object theImg = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])theImg);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
you can do this
create procedure SelectEmployeeImage(#employee int)
as
begin
SELECT Image FROM Employees WHERE EmployeeId = #EmployeeId
end
then your code will be this form
public Stream SelectEmployeeImageByID(int theID)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString());
string sql = "SelectEmployeeImage";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmployeeId", theID);
connection.Open();
object theImg = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])theImg);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
hope this will help you
Creating Stored Procedure
Create procedure SP_InsertEmployee
as
#EmployeeId int
BEGIN
SELECT Image FROM Employees WHERE EmployeeId=#EmployeeId
END
You Should Set CommandType=StoredProcedure and Rest of will be same
cmd.CommandType = CommandType.StoredProcedure;
Recommendations
Always use using which automatically disposes connections
using (SqlConnection con = new SqlConnection())
{
con.open();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
//object theImg = cmd.ExecuteScalar();
}
con.Dispose();
}
I have a method that sends two variables, an int and a delimited string, to an SQL Server proc.
Variable values (copied from debugger):
detailId: 5
fileNames: "recruiter.txt|cert.pdf"
The method:
public void InsertFiles(int detailId, string fileNames)
{
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings["PRADB"];
using (SqlConnection conn = new SqlConnection(connString.ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertFiles";
cmd.Parameters.AddWithValue("#detailId", detailId);
cmd.Parameters.AddWithValue("#fileNames", fileNames);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string exc = ex.ToString();
}
finally
{
conn.Close();
}
}
}
Here is the proc:
ALTER PROCEDURE [dbo].[InsertFiles]
#detailId int,
#fileNames varchar(max)
AS
BEGIN
SET NOCOUNT ON;
insert into [dbo].[PRA_Files] (detailId, fileNames)
values (#detailId, #fileNames)
END
The exception received when debugging:
{"Incorrect syntax near 'dbo'."}
Yet when I execute from the proc:
exec [dbo].[InsertFiles] 5, "recruiter.txt|cert.pdf"
It works fine. There error isn't code side as it is being caught in the catch block of the method above. I'm stumped.
You need to specify that the command is a stored procedure:
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertFiles";
cmd.Parameters.AddWithValue("#detailId", detailId);
cmd.Parameters.AddWithValue("#fileNames", fileNames);
cmd.CommandType = CommandType.StoredProcedure;