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);
Related
I'm new in c# and want to call store procedure in the sql server database ,for that purpose write this code:
using (SqlConnection con = new SqlConnection("Data Source=ipaddress;Initial Catalog=database;User ID=userid;Password=password;"))
{
using (SqlCommand cmd = new SqlCommand("exec web.sp_getTotalBillPayam "+Convert.ToInt64(phoneNumber) +",'"+password.Trim()+"',72107603,1067", con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
when run that code every thing is ok but store procedure not return to me any result ,goto debug i realized in this line run:
SqlDataReader reader = cmd.ExecuteReader();
but debugger not go to the next line of code and wait that line run finish,after 5 min that line not finish and dont go next line of code,what happen?How can i solve that problem?thanks.
Your command is not attached to your connection-- and your use of parameters is dangerous. Try this instead:
EDIT: Sorry, your command is attached to the connection, didn't see that being passed in. Either way, this is the correct pattern for calling a stored proc
using (SqlConnection con = new SqlConnection("Data Source=ipaddress;Initial Catalog=database;User ID=userid;Password=password;")) {
con.Open();
using (SqlCommand cmd = con.CreateCommand()) {
cmd.CommandText = "web.sp_getTotalBillPayam";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//repeat this for each parameter
var parameter = cmd.CreateParameter();
parameter.ParameterName = "PhoneNumber"; //this must match whatever your parameters are to your stored proc
parameter.DbType = System.Data.DbType.Int64;
parameter.Direction = System.Data.ParameterDirection.Input;
parameter.Value = phoneNumber;
cmd.Parameters.Add(parameter);
...
//if you have an OUTPUT result from your proc, add a a parameter called RETURNS with a direction of ParameterDirection.Return and check value AFTER executing
using (SqlDataReader reader = cmd.ExecuteReader()) {
//if your results are a SELECT query they will be here
}
}
}
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();
Trying to create a asp.net c# form for learning purposes at home and i'm absolutely struggling to connect to my storedprocedure.
I'm definitely in the right database as when I start the database by cmdprompt and connect to it via datasource in visual design it connects and finds the stored procedure. So there must be something I am doing wrong? I've been searching Google for about 30-40 minutes now and everything I've tried hasn't resolved my issue. Any suggestions please?
const string constring = #"Data Source=(localdb)\ProjectsV12;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";
public static int InsertEnquiry(string Name, string Subject, string Email, string Message, string Phone) {
//default ticketid of 0 which will be changed to -1 if an error or greater than 0 if successful
int TicketID = 0;
if (String.IsNullOrEmpty(Phone)) Phone = "0";
using (var conn = new SqlConnection(constring)) {
//create command
SqlCommand command = new SqlCommand();
//tell the command which connection its using
command.Connection = conn;
//inform command that it is a stored procedure and the name of stored procedure
command.CommandText = "InsertEnquiry";
command.CommandType = CommandType.StoredProcedure;
//add the parameters to the sqlcommand
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.NVarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#Subject", SqlDbType.NVarChar)).Value = Subject;
command.Parameters.Add(new SqlParameter("#Phone", SqlDbType.NVarChar)).Value = Phone;
command.Parameters.Add(new SqlParameter("#Email", SqlDbType.NVarChar)).Value = Email;
command.Parameters.Add(new SqlParameter("#Message", SqlDbType.NVarChar)).Value = Message;
// try run command and set TicketID to the row inserted into the table.
try {
conn.Open();
//run command
command.ExecuteNonQuery();
//return scope identity of row.
TicketID = (int)command.Parameters["#TicketID"].Value;
}
catch (Exception e) {
//show -1 to state there is an error
TicketID = -1;
}
}
return TicketID;
}
}
1st
I think you are connected to the wrong db, probably you are in master.
Run this piece of code and check the name of the database and see if it's the one that you want.
public static string checkDB()
{
string dbName = "";
using (var conn = new SqlConnection(constring))
{
//create command
SqlCommand command = new SqlCommand();
//tell the command which connection its using
command.Connection = conn;
//inform command that it is a stored procedure and the name of stored procedure
command.CommandText = "select DB_NAME()";
command.CommandType = CommandType.Text;
// try run command and set TicketID to the row inserted into the table.
try
{
conn.Open();
//run command
SqlDataReader reader = command.ExecuteReader();
reader.Read();
dbName = reader[0].ToString();
}
catch (Exception e)
{
}
}
return dbName;
}
2nd
You are trying to get the value from the parameter #TicketID but you didn't specify this parameter as an output parameter.
command.Parameters.Add("#TicketID", SqlDbType.Int).Direction = ParameterDirection.Output;
EDIT1:
This is how do you put the db name in the connection string:
const string constring = #"Data Source=(localdb)\ProjectsV12;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;Initial Catalog=MY_DB_NAME";
I am getting following error when calling a stored procedure in SQL Server from C#:
Line 1: Incorrect syntax near 'spGet_Data'.
Here is my code:
public string GetData (string destinationFile)
{
string conectionString = "uid=One_User;pwd=One_Password;database=One_Database;server=One_Server";
SqlConnection con = new SqlConnection(conectionString);
SqlCommand sqlCmd = new SqlCommand();
string returnValue = string.Empty;
string procedureName = "spGet_Data";
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd = new SqlCommand(procedureName, con);
sqlCmd.Parameters.AddWithValue("#FileName", destinationFile);
con.Open();
var returnParameter = sqlCmd.Parameters.Add("#ret", SqlDbType.VarChar);
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.ExecuteNonQuery();
returnValue = returnParameter.Value.ToString();
con.Close();
return returnValue;
}
Procedure itself returning data properly, I checked connection it is in Open state.
What else it can be?
Thank you.
The problem lies in the fact that you create the command two times.
After the first initialization you set correctly the CommandType to StoredProcedure, but once again you created the command and this time you forgot to set the CommandType
Just remove the first initialization, leave only the second one and move the CommandType setting after the initialization
SqlConnection con = new SqlConnection(conectionString);
string returnValue = string.Empty;
string procedureName = "spGet_Data";
SqlCommand sqlCmd = new SqlCommand(procedureName, con);
sqlCmd.CommandType = CommandType.StoredProcedure;
You create a SqlCommand object, then set it's CommandType property, then overwrite it by calling new on your command object again. Written out correctly, your code should look like this:
public string GetData (string destinationFile)
{
string conectionString = "uid=One_User;pwd=One_Password;database=One_Database;server=One_Server";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(procedureName, con);
sqlCmd.CommandType = CommandType.StoredProcedure;
string returnValue = string.Empty;
string procedureName = "spGet_Data";
sqlCmd.Parameters.AddWithValue("#FileName", destinationFile);
con.Open();
var returnParameter = sqlCmd.Parameters.Add("#ret", SqlDbType.VarChar);
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.ExecuteNonQuery();
returnValue = returnParameter.Value.ToString();
con.Close();
return returnValue;
}
Also, I would highly suggest that you surround your SqlConnection and SqlCommand objects with the Using Statement. Much like this:
public string GetData (string destinationFile)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand sqlCmd = new SqlCommand(procedureName, con))
{
}
}
}
The benefit of doing it this way is cleaner code and since your command and connection objects implement IDisposable, they will be handled by GC once they fall out of scope.
By the way, you have 'conectionString' misspelled; I fixed it in my code examples.
Whoops. This is being done, albeit incorrectly. See the other answer.
See SqlCommand.CommandType. You need to tell it to be treated as an sproc call. E.g.
sqlCmd.CommandType = CommandType.StoredProcedure;
Otherwise it results in an invalid SQL statement (i.e. running spGet_Data verbatim in an SSMS query should produce a similar messages).
I am new to ADO.net. I actually created a sample database and a sample stored procedure. I am very new to this concept. I am not sure of how to make the connection to the database from a C# windows application. Please guide me with some help or sample to do the same.
Something like this... (assuming you'll be passing in a Person object)
public int Insert(Person person)
{
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand dCmd = new SqlCommand("InsertData", conn);
dCmd.CommandType = CommandType.StoredProcedure;
try
{
dCmd.Parameters.AddWithValue("#firstName", person.FirstName);
dCmd.Parameters.AddWithValue("#lastName", person.LastName);
dCmd.Parameters.AddWithValue("#age", person.Age);
return dCmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
It sounds like you are looking for a tutorial on ADO.NET.
Here is one about straight ADO.NET.
Here is another one about LINQ to SQL.
This is the usual pattern (it might be a bit different for different databases, Sql Server does not require you to specify the parameters in the command text, but Oracle does, and in Oracle, parameters are prefixed with : not with #)
using(var command = yourConnection.CreateCommand())
{
command.CommandText = "YOUR_SP_CALL(#PAR1, #PAR2)";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new OdbcParameter("#PAR1", "lol"));
command.Parameters.Add(new OdbcParameter("#PAR2", 1337));
command.ExecuteNonQuery();
}
Something like this:
var connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
var conn = new SqlConnection(connectionString);
var comm = new SqlCommand("YourStoredProc", conn) { CommandType = CommandType.StoredProcedure };
try
{
conn.Open();
// Create variables to match up with session variables
var CloseSchoolID = Session["sessCloseSchoolID"];
// SqlParameter for each parameter in the stored procedure YourStoredProc
var prmClosedDate = new SqlParameter("#prmClosedDate", closedDate);
var prmSchoolID = new SqlParameter("#prmSchoolID", CloseSchoolID);
// Pass the param values to YourStoredProc
comm.Parameters.Add(prmClosedDate);
comm.Parameters.Add(prmSchoolID);
comm.ExecuteNonQuery();
}
catch (SqlException sqlex)
{
}
finally
{
conn.Close();
}
If using SQL Server:
SqlConnection connection = new SqlCOnnection("Data Source=yourserver;Initial Catalog=yourdb;user id=youruser;passowrd=yourpassword");
SqlCommand cmd = new SqlCommand("StoredProcName", connection);
cmd.CommandType=StoredProcedureType.Command;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
If not then replace Sql with Ole and change the connection string.
Here is a good starting point http://support.microsoft.com/kb/310130
OdbcConnection cn;
OdbcCommand cmd;
OdbcParameter prm;
OdbcDataReader dr;
try {
//Change the connection string to use your SQL Server.
cn = new OdbcConnection("Driver={SQL Server};Server=servername;Database=Northwind;Trusted_Connection=Yes");
//Use ODBC call syntax.
cmd = new OdbcCommand("{call CustOrderHist (?)}", cn);
prm = cmd.Parameters.Add("#CustomerID", OdbcType.Char, 5);
prm.Value = "ALFKI";
cn.Open();
dr = cmd.ExecuteReader();
//List each product.
while (dr.Read())
Console.WriteLine(dr.GetString(0));
//Clean up.
dr.Close();
cn.Close();
}
catch (OdbcException o) {
MessageBox.Show(o.Message.ToString());
}