I want to show the stored procedure but i am getting the error of Procedure SPselcocpd has no parameters and arguments were supplied.
cs page
lbllgintype.Text = com;
lblname.Text = com1;
sqlq = "";
sqlq = "select [name] from admin where userid='" + com1 + "'";
SqlDataAdapter da1 = new SqlDataAdapter(sqlq, con);
DataSet ds = new DataSet();
da1.Fill(ds);
name.Text = "";
name.Text = ds.Tables[0].Rows[0][0].ToString();
SqlCommand cmd = new SqlCommand("SPselcocpd");
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#comname", comname.Text);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataSet dt1 = new DataSet();
da2.Fill(dt1);
con.Open();
brand.Items.Add("<--select-->");
for (int i = 0; i < dt1.Tables[0].Rows.Count; i++)
{
brand.Items.Add(dt1.Tables[0].Rows[i][0].ToString());
}
con.Close();`
SQL STORED PROCEDURE
alter procedure SPselbdralt
#comname varchar(100)
as
begin
select brandname from rpmallot where comname=(select id from companydetails where comname=#comname)
end
please solve my problem as soon as possible I am working on a live project
Please make sure, You are using the correct sp
I want to show the stored procedure but i am getting the error of
Procedure SPselcocpd has no parameters and arguments were
supplied.
In code you are calling different SP SPselcocpd
SqlCommand cmd = new SqlCommand("SPselcocpd"); // Here it is SPselcocpd
And SQL SP is
alter procedure SPselbdralt
Confirm that you are calling the correct SP
You are calling wrong stored procedure.
Change
SqlCommand cmd = new SqlCommand("SPselcocpd");
To
SqlCommand cmd = new SqlCommand("SPselbdralt");
Related
I have a stored procedure with parameters, which i want to submit the parameters in a view which returns a index of the list. How do i go about this in my controller
CREATE PROCEDURE [dbo].[spFlugReport]
(
#AccNo INTEGER,
#DateFrom DATE,
#DateTo DATE
)
AS
BEGIN
SELECT *
FROM [dbo].[KIRData]
WHERE AccNo = #AccNo
AND StartDate >= #DateFrom
AND EndDate <= #DateTo
AND Prod = 'Air'
END
C# code:
public ActionResult Report()
{
using(DataModel db = new DataModel())
{
SqlParameter[] param = new SqlParameter[] {
new SqlParameter("#AccNo ,"),
new SqlParameter("#DateFrom ,"),
new SqlParameter("#DateTo ,")
};
}
}
welcome to stack overflow. Here is a useful link that could help you to achieve what you need to do.
https://csharp-station.com/Tutorial/AdoDotNet/Lesson07
and here is one with a similar question to your problem How to execute a stored procedure within C# program
However, here is an quick example of what you need to pass a parameter to a stored procedure.
// create and open a connection object
SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("CustOrderHist", conn);
// 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("#CustomerID", custId));
// execute the command
SqlDataReader rdr = cmd.ExecuteReader();
Hope this helps you.
I believe you're looking for something like this. If not, could you provide more detail.
DataTable database = new DataTable();
string dbString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(dbString))
using (SqlCommand cmd = new SqlCommand("dbo.spFlugReport", con))
{
using(DataModel db = new DataModel())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AccNo", AccNo);
cmd.Parameters.AddWithValue("#DateFrom", DateFrom);
cmd.Parameters.AddWithValue("#DateTo", DateTo);
con.Open();
cmd.ExecuteNonQuery();
}
}
This link is how you created a ConnectionString for YourConnection: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string
In sql I normally execute my procedure using
exec dbo.usp_FCS 'TIMV','serial'
And I tried something somewhat the same in c# but it seems I got this wrong
using (SqlConnection connection = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password="))
{
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" + "'" + MachineName + " ','serial' " , connection))
{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch (SqlException ex)
{
label6.Visible = true;
label6.Text = string.Format("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
}
}
My question is,how can I give those 2 inputs 'TIMV' and 'serial' of my stored procedure using c#?
Edit:
I tried something like this:
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" , connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#p2", SqlDbType.VarChar).Value = "serial";
try
{ my code...
And it is still not working
The most correct way to add a parameter to an SqlCommand is through the Add method that allows you to specify the datatype of the parameter and, in case of strings and decimals, the size and the precision of these values. In that way the Database Engine Optimizer can store your query for reuse and be a lot faster the second time you call it. In your case I would write
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 20).Value = MachineName;
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20).Value = "serial";
This assumes that your stored procedure receives two parameters named EXACTLY #mname and #serial, the type of the parameters is NVarChar and the length expected is 20 char. To give a more precise answer we need to see at least the first lines of the sp.
In your code above also the execution of the command is missing. Just creating the command does nothing until you execute it. Given the presence of an SqlDataAdapter I think you want to fill a DataSet or a DataTable and use this object as DataSource of your grid. Something like this
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
yourDataGrid.DataSource = dt;
And if this is an ASP.NET app, also the DataBind call
yourDataGrid.DataBind();
You use the Parameters collection of the SqlCommand class to send parameters to a stored procedure.
Suppose your parameter names are #p1 and #p2 (Please, for your sake, don't use names like this ever) - your c# code would look like this:
using (var cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya", connection))
{
cmd..CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#21", SqlDbType.VarChar).Value = "serial";
try
{
// rest of your code goes here....
Note: use the SqlDbType value that fits the parameters data type.
Try this:
DataSet ds = new DataSet("dts");
using (SqlConnection conn = new SqlConnection
("Data Source=;Initial Catalog=;User ID=;Password="))
{
try
{
SqlCommand sqlComm = new SqlCommand("usp_FCS_GetUnitInfo_Takaya",conn);
sqlComm.Parameters.AddWithValue("#p1", MachineName);
sqlComm.Parameters.AddWithValue("#p2", "serial");
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
catch (Exception e)
{
label6.Visible = true;
label6.Text = string.Format
("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
I'm beginner in C# and stored procedure and this application write for first time, I want to write a simple application to run a stored procedure on the my SQL Server, for more explain I write this stored procedure in SQL Server:
ALTER PROCEDURE [dbo].[CDRCOLLECT]
AS
BEGIN
EXEC xp_cmdshell 'bcp "SELECT "028",rtrim(ltrim(ANUMBER)),rtrim(ltrim(BNUMBER)),rtrim(ltrim(DATE)),rtrim(ltrim(TIME)),rtrim(ltrim(DURATION)) FROM [myTestReport].[dbo].[CDRTABLE]" queryout f:\newOUTPUT.txt -S DESKTOP-A5CFJSH\MSSQLSERVER1 -Uuser -Ppass -f "f:\myFORMAT.fmt" '
print 'run successfully!'
END
and with this code in the C# windows application want to call that stored procedure:
SqlConnection sqlConnection;
try {
sqlConnection = new SqlConnection(conn);
SqlCommand command = new SqlCommand("CDRCOLLECT", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
//return command.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("RUN SUCCESSFULL");
}
catch (Exception p)
{
MessageBox.Show(p.ToString());
}
but that procedure is not run, what happened? How can I solve that?
For select command in stored procedure
sqlConnection = new SqlConnection(conn);
System.Data.SqlClient.SqlDataAdapter SqlDataAdapter1 = new System.Data.SqlClient.SqlDataAdapter("CDRCOLLECT", sqlConnection);
SqlDataAdapter1.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
//for add parameter
//SqlDataAdapter1.SelectCommand.Parameters.Add("#param1", System.Data.SqlDbType.NVarChar);
//SqlDataAdapter1.SelectCommand.Parameters["#param1"].Value = DropDownList1.SelectedValue;
System.Data.DataSet DataSet1 = new System.Data.DataSet();
SqlDataAdapter1.Fill(DataSet1 , "0");
if (DataSet1.Tables["0"].Rows.Count > 0)
{
//you can use DataSet1.Tables["0"] for access your output data
}
For insert command with parameter for example
System.Data.SqlClient.SqlCommand scom = new System.Data.SqlClient.SqlCommand("CDRCOLLECT", sqlConnection);
scom.CommandType = System.Data.CommandType.StoredProcedure;
scom.Parameters.Add("#fName", System.Data.SqlDbType.NVarChar);
scom.Parameters.Add("#lName", System.Data.SqlDbType.NVarChar); scom.Parameters["#fName"].Value = TextBox1.Value;
scom.Parameters["#lName"].Value = TextBox2.Value;
scom.ExecuteNonQuery();
C# code:
protected void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
SqlCommand com = new SqlCommand("sp_studentresult", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", textstudentid.Text);
SqlDataAdapter adp = new SqlDataAdapter(com);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtid.Text = ds.Tables[0].Rows[0]["id"].ToString();
txttamil.Text = ds.Tables[0].Rows[0]["Tamil"].ToString();
txtenglish.Text = ds.Tables[0].Rows[0]["English"].ToString();
txtmaths.Text = ds.Tables[0].Rows[0]["Maths"].ToString();
txtscience.Text = ds.Tables[0].Rows[0]["Science"].ToString();
txtsocialscience.Text = ds.Tables[0].Rows[0]["SocialScience"].ToString();
}
SqlParameter retval = new SqlParameter("#output", SqlDbType.VarChar, 50);
retval.Direction = ParameterDirection.Output;
com.Parameters.Add(retval);
com.ExecuteNonQuery();
string Output = retval.Value.ToString();
}
Stored procedure:
ALTER PROCEDURE sp_studentresult
(
#id int,
#output varchar(50) output,
#id_student varchar(50)
)
AS
begin
SELECT * from studentresult where id_student=#id
End
IF EXISTS (SELECT * FROM student WHERE id=#id_student)
BEGIN
SET #output='EXIST'
END
I'm new to .net. When I enter student id and search I get
Procedure or function sp_studentresult has too many arguments specified.
May I know what my mistake in the above code?
Any help would be highly appreciated.
Thanks,
i bet, you are trying to return a sql result set and an output parameter, right? if so, then try the code below:
protected void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
SqlCommand com = new SqlCommand("sp_studentresult", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", textstudentid.Text);
com.Parameters.AddWithValue("#id_student", textIDStudent.Text);
SqlParameter retval2 = new SqlParameter("#output", SqlDbType.VarChar, 50);
retval2.Direction = ParameterDirection.Output;
com.Parameters.Add(retval2);
SqlDataAdapter adp = new SqlDataAdapter(com);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtid.Text = ds.Tables[0].Rows[0]["id"].ToString();
txttamil.Text = ds.Tables[0].Rows[0]["Tamil"].ToString();
txtenglish.Text = ds.Tables[0].Rows[0]["English"].ToString();
txtmaths.Text = ds.Tables[0].Rows[0]["Maths"].ToString();
txtscience.Text = ds.Tables[0].Rows[0]["Science"].ToString();
txtsocialscience.Text = ds.Tables[0].Rows[0]["SocialScience"].ToString();
}
SqlParameter retval = new SqlParameter("#output", SqlDbType.VarChar, 50);
retval.Direction = ParameterDirection.Output;
com.Parameters.Add(retval);
com.Parameters.AddWithValue("#id", textstudentid.Text);
com.Parameters.AddWithValue("#id_student", textIDStudent.Text);
com.ExecuteNonQuery();
string Output = retval.Value.ToString();
}
The stored procedure names are different.
SqlCommand com = new SqlCommand("sp_studentresult", con);
here you are referring to "sp_studentresult". The stored procedure code you have inserted is
ALTER PROCEDURE sp_searchupdate
Obviously the parameters list should be different for these procedures.
Its because the stored procedure is not getting value for all the parameters ,
Check the number of parameters which are passed to the SP from SqlCommand .
If possible update your stored procedure
You are missing parameter id_student which must supply.
Only the parameters marked as Output need not to supply.
Add it like you have added #id
e.g.
com.Parameters.AddWithValue("#id", Value);
I am not sure what will be the value for it , so you can put the correct value in place of variable Value
In the ShippedContainerSettlement program I am trying to add parameters to a SQL statement on a stored procedure that I created on the remote server (plex).
public void checkGradedSerials()
{
localTable = "Graded_Serials";
List<string> gradedHides = new List<string>();
string queryString = "call sproc164407_2053096_650214('#startDate', '" + endDate + "');";
OdbcDataAdapter adapter = new OdbcDataAdapter();
OdbcCommand command = new OdbcCommand(queryString, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#startDate", startDate);
adapter.SelectCommand = command;
connection.Open();
while (rowsCollected == false)
{
if (retries <= 5)
{
try
{
DataTable table = new DataTable();
adapter.Fill(table);
An error is thrown when I use the parameter #startDate and give it a value. However, when I run the program, and add the parameters how I have done for endDate, it runs fine?
The error I get back is:
Any ideas what I am doing wrong.
EDIT:
I have incorporated some of the changes mentioned below. Here is the code I used.
public void checkGradedSerials()
{
localTable = "Graded_Serials";
List<string> gradedHides = new List<string>();
OdbcCommand command = new OdbcCommand("sproc164407_2053096_650214", odbcConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#startDate", startDate);
command.Parameters.AddWithValue("#endDate", endDate);
OdbcDataAdapter adapter = new OdbcDataAdapter();
adapter.SelectCommand = command;
odbcConnection.Open();
while (rowsCollected == false)
{
if (retries <= 5)
{
try
{
DataTable table = new DataTable();
adapter.Fill(table);
But it doesn't seem to be receiving the parameters i am sending through as I am getting this error.
Here is the stored procedure I am using. This might look odd but remember this is working when I simply pass a string into a select command (see endDate in first code example above).
SELECT DISTINCT(Serial_No)
FROM Part_v_Container_Change2 AS CC
WHERE CC.Change_Date > #Change_Start_Date AND
CC.Change_Date <= #Change_End_Date AND
CC.Location = 'H Grading';
and the parameters are added here:
You should use the System.Data.SqlClient. You can explicitly declare the datatypes of paramaters you are sending... like this:
SqlConnection cn;
cn = new SqlConnection(ConnectionString);
SqlCommand cmd;
cmd = new SqlCommand("sproc164407_2053096_650214", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#startDate", SqlDbType.DateTime);
cmd.Parameters["#startDate"].Value = startDate;
cmd.Parameters.Add("#enddate", SqlDbType.VarChar);
cmd.Parameters["#enddate"].Value = enddate;
If you must use the ODBC, then you do have to use the ODBC CALL syntax, which does not support named parameters. So change your queryString line to:
string queryString = "{call sproc164407_2053096_650214 (?, ?)}";
Then you can add your parameters:
command.Parameters.Add("#startDate", OdbcType.DateTime).Value=startDate;
command.Parameters.Add("#endDate", OdbcType.DateTime).Value=endDate;
Use SqlCommand instead of odbc.
Just put the stored proc name in the CommandText, not a SQL statement to execute it. Adding the param values means the adapter will pass in the params in the right format. You don't need to do the string manipulation in CommandText.
If you need to use OdbcCommand then see this answer showing you need to use ? syntax for the parameters, so maybe change your CommandText back to including the 'call' or 'exec' command and parameter placeholders, then make sure you AddWithValue the params in the right order