Calling stored procedure from code-behind - c#

click here to see the tableI wrote a stored procedure to get the table value. But I don't know how to write the C# code to call the stored procedure. I want to run it in a console.
My stored procedure:
alter procedure sampleone (#createdOn nvarchar(200))
as
begin
select *
from sa_test
where createdOn = #createdOn
end
Sample trial code:
try
{
string connectionString = "(CString)";
string commandText = "sampleone";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#createdOn",25/10/2017);
cmd.CommandTimeout = 600;
conn.Open();
int affectedRows = cmd.ExecuteNonQuery();
conn.Close();
}
}
catch
{
}
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="CString" connectionString="data source=34.193.27.161;User Id=sa; Pwd=RCK$1234; Initial Catalog=rs" providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
Can anyone help me to get the C# code?

Soo, based on what you really want then your script can look different. However, you should really consider where you want to put your logic. Do you want your stored procedure to insert data or do you want C# to do it? Otherwise here is an example where your stored procedure is used for inserting data:
NOTE
My date is propberly different due to i live in another country - Just change the date back to your desired result and dateformat.
NOTE2
Consider making your createdON variable in your stored procedure as a date instead of nvarchar also.
SQL Code
--Build table for test inserts
CREATE TABLE dbo.testtable (
Name nvarchar(50),
Createdon date
)
--Insert dummy values to sa_test
INSERT INTO sa_test
values('Thomas','2017-10-10'),
('Hans','2017-12-25')
--Edit stored procedure to not just select but also insert data based on #createdOn variable
create procedure sampleone (#createdOn nvarchar(200))
as
begin
insert into testtable (Name,createdon)
select *
from sa_test
where createdon= #createdOn
end
C# Code
string conn = "Server=EGC25199;Initial Catalog=LegOgSpass;Integrated Security=True";
string query = "sampleone";
SqlConnection connDatabase = new SqlConnection(conn);
connDatabase.Open();
SqlCommand cmd = new SqlCommand(query, connDatabase);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#createdOn", SqlDbType.Date).Value = "2017-10-10";
cmd.ExecuteNonQuery();
connDatabase.Close();
C# Code with datatable and print to console
string conn = "Server=EGC25199;Initial Catalog=LegOgSpass;Integrated Security=True";
string query = "sampleone";
DataTable dt = new DataTable();
SqlConnection connDatabase = new SqlConnection(conn);
connDatabase.Open();
SqlCommand cmd = new SqlCommand(query, connDatabase);
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#createdOn", SqlDbType.Date).Value = "2017-10-10"; //Adding the selected items to parameter #check
cmd.ExecuteNonQuery();
da.Fill(dt);
foreach( DataRow row in dt.Rows)
{
Console.WriteLine();
for (int x = 0; x < dt.Columns.Count; x++)
{
Console.Write(row[x].ToString() + " ");
}
}
}
connDatabase.Close();
Result with console print
Result
My testtable is empty at first
sa_test table has 2 values i can select
When i then run my script my testtable looks like this:

cmd.Parameters.AddWithValue("#createdOn",25/10/2017);
should be like this and try :
cmd.Parameters.AddWithValue("#createdOn","25/10/2017");

You need to use ExecuteReader get return data from SP. Also there is TYPO while passing parameter.
cmd.Parameters.AddWithValue("#createdOn","25/10/2017");
Updated Code
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#createdOn","25/10/2017");
cmd.CommandTimeout = 600;
conn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
}
conn.Close();
}

You can follow this simple technique :
try
{
string connectionString = ConfigurationManager.ConnectionStrings["CString"].ConnectionString);
string commandText = "sampleone";
DataTable table = new DataTable();
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(commandText, con))
using(var da = new SqlDataAdapter(cmd))
{
cmd.Parameters.Add("#createdOn", SqlDbType.NVarChar, 50).Value = "25/10/2017";
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(table);
}
}
catch
{
}
Using the above code, your stored procedure data will be populated to the datatable table. You can then use this table for various use, like processing the data, populating the data into a datagrid etc. Another benefit of this technique is, you even don't need to open/close the connection. That will be done implicitly by the DataAdapter da

Related

How to use DataAdapter to call a stored procedure in C# with variable parameters

I am calling the following code in C# to fill a dataAdapter with a given stored procedure "sp1_name". The problem is that I want to call different stored procedures with different parameters. (All SP's do a SELECT)
Let's suppose that my stored procedure name is "SP_SOMESP", then everything works fine.
Let's suppose that my stored procedure name is "SP_SOMESP #Month= 10, #Year = 2010", then it doesn't work. It throws an exception that cannot find this stored procedure.
Any solutions?
Thanks!
//First Connection - SP1
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sp1_name, con)) //sp1_name = NAME + PARAMETERS
{
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.Fill(results2);
}
}
}
First Issue:
Parameters in a stored procedure shouldn't be included along with its name
Second Issue:
Having a space in names of stored procedure isn't a good practice.
And for code behind
using(SqlConnection con = new SqlConnection("Your Connection String Here"))
{
SqlCommand cmd = new SqlCommand("sp_SomeName", con);
cmd.CommandType = CommandType.StoredProcedure;
//the 2 codes after this comment is where you assign value to the parameters you
//have on your stored procedure from SQL
cmd.Parameters.Add("#MONTH", SqlDbType.VarChar).Value = "someValue";
cmd.Parameters.Add("#YEAR", SqlDbType.VarChar).Value = "SomeYear";
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataSet ds = new SqlDataSet();
da.Fill(ds); //this is where you put values you get from the Select command to a
//dataset named ds, reason for this is for you to fetch the value from DB to code behind
foreach(DataRow dr in ds.Tables[0].Rows) // this is where you run through the dataset and get values you want from it.
{
someTextBox.Text = dr["Month"].ToString(); //you should probably know this code
}
}
You have to add in the parameters programmatically, see SqlCommand.Parameters.
It would be something like
cmd.Parameters.AddWithValue("#Month", 10);
cmd.Parameters.AddWithValue("#Year", 2010);
This would be after the command is declared and before it is executed.
If you find that you need to delcare the data type, then try it this way
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = 10;
Check this,
using (SQLCommand cmd = new SQLCommand())
{
cmd.CommandText = "SP_SOMESP";
cmd.Parameters.Add("#Month", 10);
cmd.Parameters.Add("#Year", 2010);
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
}
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(results2);
}

C# and SQL Server: How do I get values from my SQL Table, by calling my stored procedure with C#?

I created the following stored procedure
CREATE PROCEDURE dbo.GetPoint
AS
SELECT point FROM tLocalGeo
Now I need execute that procedure from my C# Controller and save the data on a list.
As you can see the context of the problem is to get points so then I can display them on google map using javascript for that.
Can you give me some reference how to do it? Do I need SQLReader?
Thank you for your attention.
You can use SqlDataAdapter and DataSet and then can get values from dataset's first table.
SqlCommand cmd = new SqlCommand("store procedure Name", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter= new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
if(ds.Tables[0]!=null && ds.Tables[0].Rows.Count > 0)
{
//your code
}
Hope it helps.
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetPoint";
cmd.Parameters.AddWithValue("#EmployeeID", Empid) // ur input parameter//
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
GridView1.DataSource = cmd.ExecuteReader() ;
GridView1.DataBind();
}

Calling a SP which has Insert Statement and returns a table

Is it possible to call a stored procedure which will insert the details first and at the end will return a table. At present I have written two stored procedures for it: one for inserting and the other for getting the details. Now I'm trying to do both at the same time.
I'm using ExecuteScalar for inserting and ExecuteDataSet for selecting.
If your stored procedure returns data using a SELECT (of course, I suppose that you need to read that data) then you should use the SqlDataAdapter with its Fill method or an SqlDataReader using the ExecuteReader on the SqlCommand
ExecuteReader:
using(SqlConnection cn = new SqlConnection(...))
using(SqlCommand cmd = new SqlCommand(procName, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open()
using(SqlDataReader r = cmd.ExecuteReader())
{
while(r.Read())
{
// read every row and use the field values .....
}
}
}
SqlDataAdapter.Fill:
using(SqlConnection cn = new SqlConnection(...))
using(SqlCommand cmd = new SqlCommand(procName, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open()
using(SqlDataAdapter da = new SqlDataAdapter(cmd)
{
DataTable dt = new DataTable();
da.Fill(dt);
// DataTable filled with the data returned by the last SELECT in your SP
......
}
}
The SqlCommand.ExecuteReader or SqlDataAdapter.Fill will execute the stored procedure without looking at what the stored procedure does, but they expect that some kind of tabular data will be returned to loop over it
You write a procedure like this
CREATE PROCEDURE SP_Name
(
//PARAMETES
)
AS
BEGIN
//INSERT STATEMENT
//SELECT STATEMENT
END
and call ExecuteDataSet()
SqlConnection cn = new SqlConnectio(...)
SqlCommand cmd = new SqlCommand("procName", cn)
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
cmd.ExecuteScalar();
}

Stored procedure return into DataSet in C# .Net

I want to return virtual table from stored procedure and I want to use it in dataset in c# .net. My procedure is a little complex and can't find how to return a table and set it in a dataset
Here is my procedure to modify:
ALTER PROCEDURE [dbo].[Procedure1]
#Start datetime,
#Finish datetime,
#TimeRange time
AS
BEGIN
SET NOCOUNT ON;
declare #TimeRanges as TABLE (SessionStart datetime, SessionEnd datetime);
with TimeRanges as (
select #Start as StartTime, #Start + #TimeRange as EndTime
union all
select StartTime + #TimeRange, EndTime + #TimeRange
from TimeRanges
where StartTime < #Finish )
select StartTime, EndTime, Count( Test.ScenarioID ) as TotalPeaks
from TimeRanges as TR left outer join
dbo.Test as Test on TR.StartTime <= Test.SessionStartTime and Test.SessionCloseTime < TR.EndTime
group by TR.StartTime, TR.EndTime
END
Try this
DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
sqlComm.Parameters.AddWithValue("#Start", StartTime);
sqlComm.Parameters.AddWithValue("#Finish", FinishTime);
sqlComm.Parameters.AddWithValue("#TimeRange", TimeRange);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.
Create a connection string.
Create a SQL connection
Create SQL command
Create SQL data adapter
fill your dataset.
Do not forget to open and close connection. follow this link for more under standing.
You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.
SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
Now you can use the below method to pass values to Stored Procedure and get the DataSet.
public DataSet GetDataSet(string paramValue)
{
sqlcomm.Connection = sqlConn;
using (sqlConn)
{
try
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
// This will be your input parameter and its value
sqlcomm.Parameters.AddWithValue("#ParameterName", paramValue);
// You can retrieve values of `output` variables
var returnParam = new SqlParameter
{
ParameterName = "#Error",
Direction = ParameterDirection.Output,
Size = 1000
};
sqlcomm.Parameters.Add(returnParam);
// Name of stored procedure
sqlcomm.CommandText = "StoredProcedureName";
da.SelectCommand = sqlcomm;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
}
}
catch (SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
return new DataSet();
}
The following is the sample of connection string in config file
<connectionStrings>
<add name="SqlConnector"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>

Accessing SQL Server stored procedure output parameter in C#

I have a simple SQL Server stored procedure:
ALTER PROCEDURE GetRowCount
(
#count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET #count=##ROWCOUNT;
RETURN
I am trying to access the output parameter in the following C# code:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "GetRowCount";
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
SqlDataReader reader=cmd.ExecuteReader();
int ans = (int)cmd.Parameters["#count"].Value;
Console.WriteLine(ans);
But on running the code, a NullReferenceException is being thrown at the second last line of the code. Where am I going wrong? Thanks in advance!
P.S. I am new to SQL Procedures, so I referred this article.
I'd suggest you put your SqlConnection and SqlCommand into using blocks so that their proper disposal is guaranteed.
Also, if I'm not mistaken, the output parameters are only available after you've completely read the resulting data set that's being returned.
Since you don't seem to need that at all - why not just use .ExecuteNonQuery() instead? Does that fix the problem?
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("dbo.GetRowCount", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery(); // *** since you don't need the returned data - just call ExecuteNonQuery
int ans = (int)cmd.Parameters["#count"].Value;
con.Close();
Console.WriteLine(ans);
}
Also : since it seems you're only really interested in the row count - why not simplify your stored procedure to something like this:
ALTER PROCEDURE GetRowCount
AS
SELECT COUNT(*) FROM Emp WHERE age > 30;
and then use this snippet in your C# code:
con.Open();
object result = cmd.ExecuteScalar();
if(result != null)
{
int ans = Convert.ToInt32(result);
}
con.Close();
you have to specify that it is a stored procedure not a query
cmd.CommandType = CommandType.StoredProcedure;
Just use ExecuteNonQuery , you can't use ExecuteReader with out parameter in this case
cmd.ExecuteNonQuery();
Or if you want try with ExecuteScalar and ReturnValue
You should add
cmd.CommandType = CommandType.StoredProcedure
before calling it
I find the problem, its the connection string.
But now, in the code:
usuary = (string)cmd.Parameters["#USUARIO"].Value;
password = (string)cmd.Parameters["#CLAVE"].Value;
the compiler infomrs thats values are null...

Categories