what am I missing?
private void GetGeneralData(ReportPackage myPackage)
{
using (SqlConnection conn = new SqlConnection(mySqlConn))
{
using (SqlCommand cmd = new SqlCommand("[dbo].[GetStuff]", conn))
{
cmd.Parameters.AddWithValue("#id", myPackage.IdDeliverable);
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
dr.Read();
myPackage.DeployServer = dr.GetString(0);
myPackage.Connection = dr.GetString(1);
}
}
}
}
Procedure or function 'GetStuff' expects parameter '#id', which was not supplied.
Try adding
cmd.CommandType = CommandType.StoredProcedure
You're executing the stored procedure as a statement, not as a stored procedure. It is as if you opened a query window in SQL Server Management Studio and typed
[dbo].[GetStuff]
GO
So even though the stored procedure takes a parameter, since you're executing a textual statement, it can't map the parameter to anything in the text. Change the command type to CommandType.StoredProcedure.
You might find you code a little more compact, too, if you do a little refactoring, thus:
private void GetGeneralData( ReportPackage myPackage )
{
using ( SqlConnection conn = new SqlConnection(mySqlConn) )
using ( SqlCommand cmd = conn.CreateCommand() )
{
cmd.CommandType = CommandType.StoredProcedure ;
cmd.CommandText = "dbo.GetStuff" ;
cmd.Parameters.AddWithValue("#id", myPackage.IdDeliverable);
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
dr.Read();
myPackage.DeployServer = dr.GetString(0);
myPackage.Connection = dr.GetString(1);
}
}
return ;
}
ALTER Procedure [dbo].[spSearch_Stock]
(
#KeyW varchar(50),
#Empty int
)
AS
BEGIN
SET #Empty = (SELECT COUNT(Customer) FROM tbl_Stock)
IF #Empty > 0
SELECT StockID,Abb ,LotNo ,InvoiceNo ,TeaState,Customer ,Broker ,TeaGrade,Pkgs,NetWeight ,TotWeight ,PriceUSD,CurrencyRate,TotalAmtUSD,BrokerageUSD
FROM tbl_Stock
WHERE
(Abb) LIKE '%'+#Keyw+'%'
ORDER BY
StockID ASC,Abb ASC
ELSE
SELECT 'null' as StockID,'null' as Abb ,'null' as LotNo ,'null' as InvoiceNo ,'null' as TeaState,'null' as Customer ,'null' as Broker ,'null' as TeaGrade,'null' as Pkgs,'null' as NetWeight ,'null' as TotWeight ,'null' as PriceUSD,'null' as CurrencyRate,'null' as TotalAmtUSD,'null' as BrokerageUSD
END
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 am trying to return a value from the code below but I am getting an error that says:
A SqlParameter with parameter name '#vRESULT' is not contained by this SqlParameterCollection
c# Code:
public int userLogin()
{
string connStr = ConfigurationManager.ConnectionStrings["conn"].ToString();
string cmdStr = #"fucn_LOg";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
try
{
conn.Open();
cmd.CommandText = cmdStr;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters[":vResult"].Direction = ParameterDirection.Output;
cmd.Parameters.Add(new SqlParameter("param1", SqlDbType.VarChar)).Value = TB_1.Text;
cmd.Parameters.Add(new SqlParameter("param2", SqlDbType.VarChar)).Value = TB_2.Text;
cmd.ExecuteScalar();
return Int32.Parse(cmd.Parameters[":vResult"].Value.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return -1;
}
}
}
the sql server function code below with returning parameter DECLARE #vResult int
CREATE FUNCTION USER_LOGIN(#USER_NAME VARCHAR(60),
#PWD VARCHAR(60))
RETURNS INT
AS BEGIN
DECLARE #vResult int
SELECT #vRESULT=COUNT(*)
FROM OPER
WHERE UPPER(UNAM)=UPPER(#USER_NAME)
AND PSW=#PWD
IF #vResult=1
SET #vResult=1
ELSE
SET #vResult= -1
RETURN #vResult
END
Just Get result from Stroed Procedure like this:
var result = cmd.ExecuteScalar();
return Int32.Parse(result.ToString());
This gets first and Only result from Stored Procedure.
Also recommend simplify your code Like this:
public int userLogin() {
string connStr = ConfigurationManager.ConnectionStrings["conn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand("fucn_LOg", conn)) {
try {
cmd.Connection.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#param1", TB_1.Text);
cmd.Parameters.AddWithValue("#param2", TB_2.Text);
var result = cmd.ExecuteScalar();
return Int32.Parse(result.ToString());
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
return -1;
}
finally {
if (cmd.Connection.State != ConnectionState.Closed) cmd.Connection.Close();
}
}
}
And your Stored procedure should looks Like this:
CREATE PROCEDURE fucn_LOg
(
#param1 nvarchar(max),
#param2 nvarchar(max)
)
AS
BEGIN
SET NOCOUNT ON;
if (exists(select * from tbUsers where flLogin = #param1 and flPassword = #param2))
begin
return 1;
end
else
begin
return 0;
end
END
GO
OR
CREATE PROCEDURE fucn_LOg
(
#param1 nvarchar(max),
#param2 nvarchar(max)
)
AS
BEGIN
SET NOCOUNT ON;
select COUNT(*) from tbUsers where flLogin = #param1 and flPassword = #param2
END
GO
Several problems.
First, you don't need the cmd.Parameters.Clear();, as you just establish a new cmd.
Second, use # for SQL Server parameters.
Third, a parameter named vResult is not set, so cmd.Parameters[":vResult"].Direction is invalid. You need to assign its type and value. Make sure your stored procedure has this parameter set with correct SQL data type.
Lastly, I guess you return the vResult in your stored procedure like select #vResult; so make it a new vResult = function(vResult). But no, it is not how SQL Server work. It won't change your input parameter even though you return your #vResult. While, ExecuteScaler does. So, simply get your result back by var result = cmd.ExecuteScalar();.
You are getting data from a stored procedure, not getting back the parameter you sent. That's the supposed correct way.
conn.Open();
cmd.CommandText = cmdStr;
cmd.CommandType = CommandType.StoredProcedure;
//Base on sql you provided, it is no need for this part.
/*
SqlParameter vResult = new SqlParameter();
vResult.ParameterName = "#vResult";
vResult.Direction = ParameterDirection.Output;
vResult.SqlDbType = System.Data.SqlDbType.???;
vResult.Value = ???;
cmd.Parameters.Add(vResult);
*/
cmd.Parameters.Add("#param1", SqlDbType.VarChar).Value = TB_1.Text;
cmd.Parameters.Add("#param2", SqlDbType.VarChar).Value = TB_2.Text;
var result = cmd.ExecuteScalar();
return Int32.Parse(result.ToString());
This is hard to debug without the SP, but a couple of things jump out.
First, you need to use the '#' character as a prefix for your parameter names, not a colon.
Second, you should define your output parameter like this:
SqlParameter outputParam = new SqlParameter("#vResult", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outputParam);
I have an asp app that should be able to let a user update an entry in a sql server database. When I run my stored procedure though in my method, nothing happens to the database.
public void updateFeature(Feature updatedFeature)
{
using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString(updatedFeature.Environment)))
using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "usp_UpdateFeature";
sqlCommand.Parameters.AddWithValue("#FeatureName", updatedFeature.FeatureName);
sqlCommand.Parameters.AddWithValue("#FeatureID", updatedFeature.FeatureID);
sqlCommand.Parameters.AddWithValue("#FeatureDescription", updatedFeature.Description);
sqlCommand.Parameters.AddWithValue("#FieldName", updatedFeature.FieldName);
sqlCommand.Parameters.AddWithValue("#OnOffSwitch", updatedFeature.IsOn);
sqlCommand.Parameters.AddWithValue("#ChannelID", updatedFeature.ChannelID);
sqlCommand.Parameters.AddWithValue("#ProductID", updatedFeature.ProductID);
sqlConnection.Open();
int numberOfRowsChanged = sqlCommand.ExecuteNonQuery();
}
}
and my stored procedure looks like this
ALTER PROCEDURE [dbo].[usp_UpdateFeature]
(
#FeatureID int,
#FeatureName varchar(30),
#FeatureDescription varchar(200) = null,
#FieldName varchar(40),
#OnOffSwitch bit,
#ChannelID varchar(3),
#ProductID varchar(2)
)
AS
SET NOCOUNT ON
UPDATE FM_Feature
SET FeatureName = #FeatureName,
FeatureDescription = #FeatureDescription,
FieldName = #FieldName,
OnOffSwitch = #OnOffSwitch,
ProductID = #ProductID,
ChannelID = #ChannelID
WHERE FeatureID = #FeatureID
The numberOfRowsChanged parameter returns -1 but I do not get any exceptions or errors. Is there something that I am missing or not understanding?
I think that you need to open your connection before you create your command, i hope that will be helpful for you .
using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString(updatedFeature.Environment))
sqlConnection.Open();
using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "usp_UpdateFeature";
sqlCommand.Parameters.AddWithValue("#FeatureName", updatedFeature.FeatureName);
sqlCommand.Parameters.AddWithValue("#FeatureID", updatedFeature.FeatureID);
sqlCommand.Parameters.AddWithValue("#FeatureDescription", updatedFeature.Description);
sqlCommand.Parameters.AddWithValue("#FieldName", updatedFeature.FieldName);
sqlCommand.Parameters.AddWithValue("#OnOffSwitch", updatedFeature.IsOn);
sqlCommand.Parameters.AddWithValue("#ChannelID", updatedFeature.ChannelID);
sqlCommand.Parameters.AddWithValue("#ProductID", updatedFeature.ProductID);
int numberOfRowsChanged = sqlCommand.ExecuteNonQuery();
}
enjoy it .
I am trying to call an Oracle stored procedure from a C# program. I am using a SYS_REFCURSOR an the output of the stored procedure. I am getting invalid SQL error when I reach the line
OracleDataReader reader = cmd.ExecuteReader()
in my C# program. I can't figure out why I am getting this invalid SQL error.
Here is the C# code:
private void button1_Click(object sender, EventArgs e)
{
string custname;
int custnbr;
List<Customer> customers = new List<Customer>();
string oradb = "User Id=XXXXX;Password=XXXXX;Data Source=IP:PORT/xxxx;Pooling=false;";
OracleConnection conn = new OracleConnection(oradb);
try
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PROCEDURE_TEST";
OracleParameter oraP = new OracleParameter();
oraP.ParameterName = "R_RECORDSET";
oraP.OracleDbType = OracleDbType.RefCursor;
oraP.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(oraP);
cmd.CommandType = CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
custnbr = reader.GetInt32(0);
custname = reader.GetString(1);
Customer custTemp = new Customer(custnbr, custname);
customers.Add(custTemp);
}
foreach (var cust in customers)
{
textBox1.AppendText("Customer Number: " + cust.custnbr + "\t");
textBox1.AppendText("Customer Name: " + cust.custname + "\r\n");
}
}
catch(Exception ex)
{
textBox1.AppendText(ex.ToString());
conn.Close();
}
}
Here is the Oracle stored procedure:
create or replace PROCEDURE PROCEDURE_TEST
( R_RECORDSET OUT SYS_REFCURSOR) AS
BEGIN
OPEN R_RECORDSET FOR
SELECT POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT, SUM(POTCHARGEQTY), SUM(POTCHARGEAMOUNT)
FROM riowner.ccum_customer customer
WHERE ic.collection_Datetime =
TO_DATE('30-SEP-2015 23:59:59','DD-MON-YYYY HH24:MI:SS')
GROUP BY POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT;
END PROCEDURE_TEST;
cmd.CommandType = CommandType.Text;
should be
cmd.CommandType = CommandType.StoredProcedure;
As an alternative to MethodMan's answer, you should be able to keep the command type as Text, but change your SQL command to this:
cmd.CommandText = "BEGIN PROCEDURE_TEST END;";
MethodMan's method is better if you just need to call one procedure, but the way I did it above would allow you to do more procedures, so it's something to be aware of in the future.
This is my Stored Procedure.
DECLARE #listStr VARCHAR(500)
select #listStr = COALESCE(#listStr + ';' ,'') + eml_ID from EmailGroup where eml_Level=3 and eml_Stat=1
SELECT #listStr
I dont have problem when I call this SP on my code behind. What I want to do is to put this SP on my code behind. This is what i tried in my code behind.
using (SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
{
string stR = #"select #listStr = COALESCE(#listStr + ';' ,'') + eml_ID from EmailGroup where eml_Level=3 and eml_Stat=1";
using (SqlCommand cmD = new SqlCommand(stR, sqlConn))
{
sqlConn.Open();
SqlDataReader dR = cmD.ExecuteReader();
cmD.Parameters.Add("#listStr", SqlDbType.VarChar);
while (dR.Read())
{
string emailFullName = Session["UserFullName"].ToString();
string email = Session["UserEmailAdd"].ToString();
//more code here
}
When I tries this approach. I receive error "Must declare the scalar variable "#listStr".
My Question is how can i declare a variable in code behind?
You omited in code behind the variable declaration.
DECLARE #listStr VARCHAR(500);
Your code should be:
using (SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
{
string stR = #"DECLARE #listStr VARCHAR(500); select #listStr = COALESCE(#listStr + ';' ,'') + eml_ID from EmailGroup where eml_Level=3 and eml_Stat=1";
using (SqlCommand cmD = new SqlCommand(stR, sqlConn))
{
// Omitted
Beware to separate your statements with a semicolon ;
select #listStr = COALESCE(....
That should populate a variable, but will not return a result set that you can read with
while (dR.Read()) {}
You should remove the variable assignment if you are executing a query for results...
select COALESCE(....
Are you saying Stored Procedure when you mean Query? A Stored Procedure is a named "function" that expects parameters and returns data. A Stored Procedure contains one or more queries like what you wrote above.
You need to declare the value of listStr, try this:
cmD.Parameters.Add("#listStr", SqlDbType.VarChar, 15, "test");
or
cmD.Parameters.Add("#listStr", SqlDbType.VarChar).Value = "test";
And the compiler is looking for #listStr in your SELECT statement, which is not declared. You need to change your query with something like this:
using (SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
{
using (SqlCommand cmD = new SqlCommand("StoredProcName", sqlConn) { CommandType = CommandType.StoredProcedure })
{
sqlConn.Open();
SqlDataReader dR = cmD.ExecuteReader();
cmD.Parameters.Add("#listStr", SqlDbType.VarChar).Value = "test";
while (dR.Read())
{
string emailFullName = Session["UserFullName"].ToString();
string email = Session["UserEmailAdd"].ToString();
//more code here
}
}
}
You mention a stored procedure, and I strongly recommend you to leverage on separating db implementation from DAL implementation.
So first create the stored procedure in the proper DB:
USE myActualDb /* use the actual db name */
GO
CREATE PROCEDURE GetEmailList
#eml_level int, /* use the actual datatype */
#eml_stat int, /* use the actual datatype */
AS
BEGIN
DECLARE #listStr VARCHAR(500)
SELECT #listStr = COALESCE(#listStr + ';' ,'') + eml_ID
FROM EmailGroup
WHERE eml_Level = #eml_level AND eml_Stat = #eml_stat
SELECT #listStr
END
Then call the stored from the codebehind using ADO.NET SqlClient:
var emlLevel = levelValue;
var emlStat = statValue;
using (SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetEmailList";
cmd.Parameters.Add(new SqlParameter("eml_level", emlLevel));
cmd.Parameters.Add(new SqlParameter("eml_level", emlStat));
sqlConn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
/* do whatever you need with the dr result */
}
/* clean up*/
}
}