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();
Related
I have the following stored procedure and I want to obtain the value that it returns:
ALTER PROCEDURE [dbo].[ExistsItemID]
#ItemID uniqueidentifier
AS
BEGIN
IF (EXISTS (SELECT ItemID FROM Discounts WHERE ItemID = #ItemID))
BEGIN
RETURN 1
END
ELSE
BEGIN
RETURN 0
END
END
And in C# I have the following code:
using (SqlConnection sqlCon = new SqlConnection(scheduleConnection.ConnectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("ExistsItemID", scheduleConnection);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.ExecuteScalar();
SqlParameter returno = new SqlParameter();
returno.Direction = ParameterDirection.ReturnValue;
int valor = returno.Value;
}
But it has not worked for me, how can I get the value of the stored procedure? First of all, thanks
You need to add the parameter to the command before executing it. Use the Add method on the Parameters collection.
using (SqlConnection sqlCon = new SqlConnection(scheduleConnection.ConnectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("ExistsItemID", scheduleConnection);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter returno = new SqlParameter();
returno.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add(returno);
sqlCmd.ExecuteScalar();
int valor = returno.Value;
}
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
I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.
Stored procedure code:
ALTER procedure [dbo].[usp_GetNewSeqVal]
#SeqName nvarchar(255)
as
begin
declare #NewSeqVal int
set NOCOUNT ON
update AllSequences
set #NewSeqVal = CurrVal = CurrVal+Incr
where SeqName = #SeqName
if ##rowcount = 0 begin
print 'Sequence does not exist'
return
end
return #NewSeqVal
end
Code calling the stored procedure:
SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();
SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
param = cmd.Parameters.Add("#SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";
SqlDataReader reader = cmd.ExecuteReader();
I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get
the return value from my stored procedure? If more information is needed, please let me know.
You need to add a ReturnValue-direction parameter to the command:
using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = parameterStatement.getQuery();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");
// #ReturnVal could be any name
var returnParameter = cmd.Parameters.Add("#ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
conn.Open();
cmd.ExecuteNonQuery();
var result = returnParameter.Value;
}
Setting the parameter's direction to ParameterDirection.ReturnValue instructs the SqlCommand to declare it as a variable and assign the stored procedure's return value to it (exec #ReturnValue = spMyProcedure...), exactly like you would write it in SQL.
I know this is old, but i stumbled on it with Google.
If you have a return value in your stored procedure say "Return 1" - not using output parameters.
You can do the following - "#RETURN_VALUE" is silently added to every command object. NO NEED TO EXPLICITLY ADD
cmd.ExecuteNonQuery();
rtn = (int)cmd.Parameters["#RETURN_VALUE"].Value;
The version of EnterpriseLibrary on my machine had other parameters.
This was working:
SqlParameter retval = new SqlParameter("#ReturnValue", System.Data.SqlDbType.Int);
retval.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add(retval);
db.ExecuteNonQuery(cmd);
object o = cmd.Parameters["#ReturnValue"].Value;
I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:
#Result int OUTPUT
And C#:
SqlParameter result = cmd.Parameters.Add(new SqlParameter("#Result", DbType.Int32));
result.Direction = ParameterDirection.ReturnValue;
In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.
r
Result.Direction = ParameterDirection.InputOutput;
This is a very short sample of returning a single value from a procedure:
SQL:
CREATE PROCEDURE [dbo].[MakeDouble] #InpVal int AS BEGIN
SELECT #InpVal * 2; RETURN 0;
END
C#-code:
int inpVal = 11;
string retVal = "?";
using (var sqlCon = new SqlConnection(
"Data Source = . ; Initial Catalog = SampleDb; Integrated Security = True;"))
{
sqlCon.Open();
retVal = new SqlCommand("Exec dbo.MakeDouble " + inpVal + ";",
sqlCon).ExecuteScalar().ToString();
sqlCon.Close();
}
Debug.Print(inpVal + " * 2 = " + retVal);
//> 11 * 2 = 22
ExecuteScalar(); will work, but an output parameter would be a superior solution.
You can try using an output parameter. http://msdn.microsoft.com/en-us/library/ms378108.aspx
Or if you're using EnterpriseLibrary rather than standard ADO.NET...
Database db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("usp_GetNewSeqVal"))
{
db.AddInParameter(cmd, "SeqName", DbType.String, "SeqNameValue");
db.AddParameter(cmd, "RetVal", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);
db.ExecuteNonQuery(cmd);
var result = (int)cmd.Parameters["RetVal"].Value;
}
I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah
Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;
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");
I have a SQL stored procedure that returns a column value (SQL data type: nchar(1)). The stored procedure runs and comes back with desired value when a parameter is passed. Based on this returned value, I want to divert the program flow. For this I need to read the value returned in an ASP.NET C# variable, but I am not sure how can I do this.
create procedure sproc_Type
#name as nchar(10)
AS
SELECT Type FROM Table WHERE Name = #name
I want to read Type value in .cs file and want to save it for later use.
SqlConnection conn = null;
SqlDataReader rdr = null;
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(
"Stored_PROCEDURE_NAME", 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("#PARAMETER_NAME", PARAMETER_VALUE));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
var result = rdr["COLUMN_NAME"].ToString();
}
string connectionString = "(your connection string here)";
string commandText = "usp_YourStoredProc";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
// your code to fetch here.
}
conn.Close();
}