Using SQL queries in C#. Trouble with defining stored procedure - c#

I'm sharing a snippet from my code below:
string str = "select * from contacts";
DataSet dt = Global.getdatatablefromquery(str);
ExcelGrid.DataSource = dt;
ExcelGrid.DataBind();
I am changing all my queries to stored procedures, but I don't know exactly how will I define my stored procedure in this code? I want something like:
string str = "storedprocedurename";
DataSet dt = Global.getdatatablefromquery(str);
ExcelGrid.DataSource = dt;
ExcelGrid.DataBind();

You have 2 choices (as far as I know):
1. Execute it as Text by specifying EXEC explicitly.
Eg:
cmd = new SqlCommand("EXEC storedprocedurename(#p1, #p2)");
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#p1", 1);
cmd.Parameters.Add("#p2", 2);
2. You can use CommandType as StoredProcedure
Eg:
cmd = new SqlCommand("storedprocedurename");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", 1);
cmd.Parameters.Add("#p2", 2);
The difference between the 2 approaches is how message pumping happens.(source)
Using the second approach in which the CommandType is explicitly specified as StoredProcedure is more clear and cleaner.

Related

Calling stored procedure with parameter to return list

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

ExecuteNonQuery with return value in a stored procedure [duplicate]

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;

Procedure has no parameters and arguments were supplied

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");

Error when adding parameters to stored procedure call

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

System.ArgumentException: The table type parameter must have a valid type name

I am trying to pass in a user defined table type into a query in C#.
the type is defined with 2 columns (org and sub org)
this is what my code looks like:
DataSet ds = new DataSet();
try
{
DataTable FilteredOrgSubOrg = new DataTable("OrgSubOrgValueType");
FilteredOrgSubOrg.Columns.Add("org", typeof(string));
FilteredOrgSubOrg.Columns.Add("subOrg", typeof(string));
FilteredOrgSubOrg.Rows.Add(org, orgsub);
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"select * from myTable ex where year = #year' and qtr = #qtr" +
" and EXISTS(SELECT 1 FROM #OrgSubOrg tt WHERE ex.org like tt.org" +
" AND ex.orgsub = tt.suborg )"+
" order by ex.org,year, qtr DESC";
// 2. set the command object so it knows
// to execute a stored procedure
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#OrgSubOrg", FilteredOrgSubOrg));
cmd.Parameters.Add(new SqlParameter("#year", year));
cmd.Parameters.Add(new SqlParameter("#qtr", qtr));
conn.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = cmd;
sqlDA.Fill(ds);
}
}
am i passing the parameters in incorrectly?
when i do it in SQL server like so:
declare #OrgSubOrg OrgSubOrgValueType
insert into #OrgSubOrg values ('05%','00000000')
insert into #OrgSubOrg values ('03%','00000000')
------------ complete -----------------------------------
select * from myTable ex
where
year = '2013' and qtr = '1'
and EXISTS(
SELECT 1
FROM #OrgSubOrg tt
WHERE ex.org like tt.org
AND ex.orgsub = tt.suborg )
order by ex.org,year, qtr DESC
everything works like it should.
i also tried passing it in like so:
SqlParameter p = cmd.Parameters.Add(new SqlParameter("#OrgSubOrg", SqlDbType.Structured));
p.Value = FilteredOrgSubOrg;
but am getting the same error
The table type parameter '#OrgSubOrg' must have a valid type name.
could it be that i can't pass it to a SQL command, i have similar code in another place, that works great with a stored procedure...?
Set mapping to your type in SqlServer using TypeName property that: Gets or sets the type name for a table-valued parameter, that has to fix .
p.TypeName = "dbo.MyType";
Check as well Table-Valued Parameters post
Note that this may also happen when you're executing a stored procedure and you don't have the SqlCommand.CommandType set to CommandType.StoredProcedure, as such:
using (SqlCommand cmd = new SqlCommand("StoredProcName", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
You can get this error also when you wanna pass table params into stored procedure. There is happen if you use entity famework Context.Database.SqlQuery(). You must necessary set TypeName property for your table params.
SqlParameter codesParam = new SqlParameter(CODES_PARAM, SqlDbType.Structured);
SqlParameter factoriesParam = new SqlParameter(FACTORIES_PARAM, SqlDbType.Structured);
codesParam.Value = tbCodes;
codesParam.TypeName = "[dbo].[MES_CodesType]";
factoriesParam.Value = tbfactories;
factoriesParam.TypeName = "[dbo].[MES_FactoriesType]";
var list = _context.Database.SqlQuery<MESGoodsRemain>($"{SP_NAME} {CODES_PARAM}, {FACTORIES_PARAM}"
, new SqlParameter[] {
codesParam,
factoriesParam
}
).ToList();

Categories

Resources