473,320 Members | 1,946 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

HOW TO: Call a Parameterized Stored Procedure by Using ADO.NET and Visual C# .NET

HOW TO: Call a Parameterized Stored Procedure by Using ADO.NET and
Visual C# .NET
View products that this article applies to.
This article was previously published under Q310070
For a Microsoft Visual Basic .NET version of this article, see 308049.
For a Microsoft Visual C++ .NET version of this article, see 310071.
For a Microsoft Visual J# .NET version of this article, see 320627.

This article refers to the following Microsoft .NET Framework Class
Library namespaces:
System.Data.SqlClient
System.Data.OleDb
IN THIS TASK
SUMMARY

Use DataReader to Return Rows and Parameters
Use the ExecuteScalar Method of the Command Object
Use the ExecuteNonQuery Method of the Command Object
REFERENCES
SUMMARY
There are several ways to use ADO.NET to call a stored procedure and
to get back return values and return parameters, including:
Use a DataSet object to gather the returned rows and to work with
these rows in addition to the return values and the return parameters.
Use a DataReader object to gather the returned rows, to move through
these rows, and then to gather return values and return parameters.
Use the ExecuteScalar method to return the value from the first column
of the results' first row with the return values and the return
parameters. This is most useful with aggregate functions.
Use the ExecuteNonQuery method to return only the return parameters
and the return values. Any returned rows are discarded. This is most
useful for executing action queries.
This article demonstrates the last three methods and uses both the
SqlCommand and the OleDbCommand objects. Make sure that you copy only
the code for the managed provider that you are using. If you are not
sure which managed provider you should use, visit the following
Microsoft Developer Network Web site:
..NET Data Providers
http://msdn.microsoft.com/library/de...tproviders.asp

In each of the samples in this article, the parameters are added to
the Parameters collection of the Command object. When you use the
SqlCommand object, you do not have add the parameters in any
particular order, but the parameters must have the correct name. When
you use the OleDbCommand object, you must add the parameters in the
correct order, and you cannot use the parameters by name.

back to the top
Use DataReader to Return Rows and Parameters
You can use the DataReader object to return a read-only, forward-only
stream of data. The information that the DataReader contains can come
from a stored procedure. This example uses the DataReader object to
run a stored procedure that has an input and an output parameter and
then moves through the returned records to view the return parameters.
Create the following stored procedure on the server that is running
Microsoft SQL Server:Create Procedure TestProcedure
(
@au_idIN varchar (11),
@numTitlesOUT Integer OUTPUT
)
AS

select A.au_fname, A.au_lname, T.title
from authors as A join titleauthor as TA on
A.au_id=TA.au_id
join titles as T
on T.title_id=TA.title_id
where A.au_id=@au_idIN
set @numTitlesOUT = @@Rowcount
return (5)

Create a new Visual C# .NET Windows Application project.
Use the using statement on the System and the System.Data namespaces
so that you do not have to qualify declarations in those namespaces
later in your code. Add this code to the top of the Form code module.
Make sure to copy only the code for the provider that you have
chosen.SQL Clientusing System.Data.SqlClient;

OLE DB Data Providerusing System.Data.OleDb;

Replace the code in the private Form_Load event with the following
code:SQL ClientSqlConnection PubsConn = new SqlConnection
("Data Source=server;integrated " +
"Security=sspi;initial catalog=pubs;");
SqlCommand testCMD = new SqlCommand
("TestProcedure", PubsConn);

testCMD.CommandType = CommandType.StoredProcedure;

SqlParameter RetVal = testCMD.Parameters.Add
("RetVal", SqlDbType.Int);
RetVal.Direction = ParameterDirection.ReturnValue;
SqlParameter IdIn = testCMD.Parameters.Add
("@au_idIN", SqlDbType.VarChar, 11);
IdIn.Direction = ParameterDirection.Input;
SqlParameter NumTitles = testCMD.Parameters.Add
("@numtitlesout", SqlDbType.VarChar, 11);
NumTitles.Direction = ParameterDirection.Output ;

IdIn.Value = "213-46-8915";
PubsConn.Open();

SqlDataReader myReader = testCMD.ExecuteReader();
Console.WriteLine ("Book Titles for this Author:");
while (myReader.Read())
{
Console.WriteLine ("{0}", myReader.GetString (2));
};
myReader.Close() ;
Console.WriteLine("Number of Rows: " + NumTitles.Value );
Console.WriteLine("Return Value: " + RetVal.Value);

OLE DB Data ProviderOleDbConnection PubsConn = new OleDbConnection
("Provider=SQLOLEDB;Data Source=server;" +
"integrated Security=sspi;initial catalog=pubs;");
OleDbCommand testCMD = new OleDbCommand
("TestProcedure", PubsConn);

testCMD.CommandType = CommandType.StoredProcedure;

OleDbParameter RetVal = testCMD.Parameters.Add
("RetVal", OleDbType.Integer);RetVal.Direction =
ParameterDirection.ReturnValue;
OleDbParameter IdIn = testCMD.Parameters.Add
("@au_idIN", OleDbType.VarChar, 11);
IdIn.Direction = ParameterDirection.Input;
OleDbParameter NumTitles = testCMD.Parameters.Add
("@numtitlesout", OleDbType.VarChar, 11);
NumTitles.Direction = ParameterDirection.Output;

IdIn.Value = "213-46-8915";

PubsConn.Open();

OleDbDataReader myReader = testCMD.ExecuteReader();
Console.WriteLine ("Book Titles for this Author:");
while (myReader.Read())
{
Console.WriteLine ("{0}", myReader.GetString (2));
};
myReader.Close() ;
Console.WriteLine("Number of Rows: " + NumTitles.Value );
Console.WriteLine("Return Value: " + RetVal.Value);

Modify the connection string for the Connection object to point to the
computer that is running SQL Server.
Run the code. Notice that the DataReader retrieves the records and
then returns the parameter values. You can use the Read method of the
DataReader object to move through the returned records.

The Output window displays the titles of two books, the return value
of 5, and the output parameter, which contains the number of records
(2). Notice that you must close the DataReader in the code to see the
parameter values. Additionally, note that you do not have to move
through all of the records to see the return parameters if the
DataReader is closed.
back to the top
Use the ExecuteScalar Method of the Command Object
You can use the ExecuteScalar method of the Command object to retrieve
parameter values. Additionally, ExecuteScalar returns the first column
of the first row of the stored procedure. This is most useful for
aggregate functions as in the following example.
Create the following stored procedure on the server that is running
SQL Server:Create Procedure TestProcedure2
(
@au_idIN varchar (11)
)
As
/* set nocount on */
select count (T.title)
from authors as A join titleauthor as TA on
A.au_id=TA.au_id
join titles as T
on T.title_id=TA.title_id
where A.au_id=@au_idIN
Return(5)

Create a new Visual C# .NET Windows Application project.
Use the using statement on the System and the System.Data namespaces
so that you do not have to qualify declarations in those namespaces
later in your code. Add this code to the top of the Form code module.
Make sure that you copy only the code for the provider that you have
chosen.SQL Clientusing System.Data.SqlClient;

OLE DB Data Providerusing System.Data.OleDb;

Add the following code to the Form_Load event:SQL Clientstring
strCount;
SqlConnection PubsConn = new SqlConnection
("Data Source=server;integrated " +
"Security=sspi;initial catalog=pubs;");
SqlCommand testCMD = new SqlCommand
("TestProcedure2", PubsConn);

testCMD.CommandType = CommandType.StoredProcedure;

SqlParameter RetVal = testCMD.Parameters.Add
("RetVal", SqlDbType.Int);
RetVal.Direction = ParameterDirection.ReturnValue;
SqlParameter IdIn = testCMD.Parameters.Add
("@au_idIN", SqlDbType.VarChar, 11);
IdIn.Direction = ParameterDirection.Input;

IdIn.Value = "213-46-8915";

PubsConn.Open();

strCount =testCMD.ExecuteScalar ().ToString() ;

Console.WriteLine("Number of Rows: " + strCount );
Console.WriteLine("Return Value: " + RetVal.Value);

OLE DB Data Providerstring strCount;
OleDbConnection PubsConn = new OleDbConnection
("Provider=SQLOLEDB;Data Source=server;" +
"integrated Security=sspi;initial catalog=pubs;");
OleDbCommand testCMD = new OleDbCommand
("TestProcedure2", PubsConn);

testCMD.CommandType = CommandType.StoredProcedure;

OleDbParameter RetVal = testCMD.Parameters.Add
("RetVal", OleDbType.Integer);
RetVal.Direction = ParameterDirection.ReturnValue;
OleDbParameter IdIn = testCMD.Parameters.Add
("@au_idIN", OleDbType.VarChar, 11);
IdIn.Direction = ParameterDirection.Input;

IdIn.Value = "213-46-8915";

PubsConn.Open();

strCount = testCMD.ExecuteScalar().ToString() ;

Console.WriteLine("Number of Rows: " + strCount);
Console.WriteLine("Return Value: " + RetVal.Value);

Modify the connection string for the Connection object to point to the
computer that is running SQL Server.
Run the code. Notice that the ExecuteScalar method of the Command
object returns the parameters. ExecuteScalar also returns the value of
column 1, row 1 of the returned rowset. Therefore, the value of
intCount is the result of the count function from the stored
procedure.
back to the top
Use the ExecuteNonQuery Method of the Command Object
This sample uses the ExecuteNonQuery method to run the query and to
return the parameter values. ExecuteNonQuery also returns the number
of records that are affected after the query runs. However,
ExecuteNonQuery does not return any rows or columns from the stored
procedure.

The ExecuteNonQuery method is most useful when you use INSERT, UPDATE,
or DELETE statements if you only have to know how many rows are
changed. In a stored procedure in which you are using only a SELECT
statement, you receive -1 because no rows are affected by the query.
Create the following stored procedure on the computer that is running
SQL Server:Create Procedure TestProcedure3
(
@au_idIN varchar (11),
@au_fnam varchar (30)
)

As
/* set nocount on */
Update authors set au_fname = @au_fnam
where au_id = @au_idin
return (5)

Create a new Visual C# .NET Windows Application project.
Use the using statement on the System and the System.Data namespaces
so that you do not have to qualify declarations in those namespaces
later in your code. Add this code to the top of the Form code module.
Make sure that you copy only the code for the provider that you have
chosen.SQL Clientusing System.Data.SqlClient;

OLE DB Data Providerusing System.Data.OleDb;

Replace the code below the private Form1_Load event in the Form1 code
module with the following code:SQL Clientstring strRowAffect;
SqlConnection PubsConn = new SqlConnection
("Data Source=server;integrated Security=sspi;" +
"initial catalog=pubs;");
SqlCommand testCMD = new SqlCommand
("TestProcedure3", PubsConn);

testCMD.CommandType = CommandType.StoredProcedure;

SqlParameter RetVal = testCMD.Parameters.Add
("RetVal", SqlDbType.Int);
RetVal.Direction = ParameterDirection.ReturnValue;
SqlParameter IdIn = testCMD.Parameters.Add
("@au_idIN", SqlDbType.VarChar, 11);
IdIn.Direction = ParameterDirection.Input;
SqlParameter FnameIn = testCMD.Parameters.Add
("@au_fnam", SqlDbType.VarChar, 30);
FnameIn.Direction = ParameterDirection.Input;

IdIn.Value = "213-46-8915";
FnameIn.Value = "Marjorie";

PubsConn.Open();

strRowAffect =testCMD.ExecuteNonQuery ().ToString() ;

Console.WriteLine("Number of Rows: " + strRowAffect );
Console.WriteLine("Return Value: " + RetVal.Value);

OLE DB Data Providerint intRowAffected;
OleDbConnection PubsConn = new OleDbConnection
("Provider=SQLOLEDB;Data Source=server;" +
"integrated Security=sspi;initial catalog=pubs;");
OleDbCommand testCMD = new OleDbCommand
("TestProcedure3", PubsConn);

testCMD.CommandType = CommandType.StoredProcedure;

OleDbParameter RetVal = testCMD.Parameters.Add
("RetVal", OleDbType.Integer);
RetVal.Direction = ParameterDirection.ReturnValue;
OleDbParameter IdIn = testCMD.Parameters.Add
("@au_idIN", OleDbType.VarChar, 11);
IdIn.Direction = ParameterDirection.Input;
OleDbParameter FnameIn = testCMD.Parameters.Add
("@au_fname", OleDbType.VarChar, 30);
FnameIn.Direction = ParameterDirection.Input;

IdIn.Value = "213-46-8915";
FnameIn.Value = "Marjorie";

PubsConn.Open();
intRowAffected = testCMD.ExecuteNonQuery();

Console.WriteLine("Number of Rows affected: " + intRowAffected);
Console.WriteLine(RetVal.Value);

Modify the connection string for the Connection object to point to the
computer that is running SQL Server.
Run the code. The Output window displays the number of affected rows
(intRowAffect) and the value of the return parameter.
back to the top
REFERENCES
For additional information, visit the following MSDN Web sites:
Introduction to the .NET Framework Class Library
http://msdn.microsoft.com/library/de...asslibrary.asp

Retrieving Data Using the DataReader
http://msdn.microsoft.com/library/de...datareader.asp

back to the top
Jul 20 '05 #1
0 6666

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Chris | last post by:
Hello everyone I want to call a DB2 7.2 stored procedure via ADO in VC++ 7.1 It has 4 parameters, the 1st and the 4th are OUTPUT and the others are INPUT params. My code looks like this:...
7
by: Malcolm Cook | last post by:
Hi, I've created and installed a custom UDF to populate my combobox, and have defined it per :...
7
by: M | last post by:
Is there any way to modify the following code so I can run it with any number of paramNames as well as any number of paramValues? So far it works with an array of paramValues, but since you can...
11
by: anony | last post by:
Hello, I can't figure out why my parameterized query from an ASP.NET page is dropping "special" characters such as accented quotes & apostrophes, the registered trademark symbol, etc. These...
1
by: Sheldon Penner | last post by:
I have been trying to build a web form using the SQL Data Adapter Configuration Wizard to create a dataset based on a parameterized stored procedure. I find that if I select "Use existing stored...
3
by: dew | last post by:
I have a stored procedure that retrieves the id of a client table, which is a guid To get that id, I have dim clientid as guid = GetClientID("OrgName") The GetClientID returns a string,...
0
by: james.peer | last post by:
I'm fairly new to this so hopefully it is a dumb mistake... I need to create a simple stored procedure along the lines of: delimiter // CREATE DEFINER='root'@'localhost' PROCEDURE Insertuser()...
1
by: Groningen | last post by:
Hi, I was wondering if someone could help me on this one. I've made a stored procedure in SQL Server Enterprise Manager. When I call the stored procedure in Visual Basic I didn't succeed to...
0
TonFrere
by: TonFrere | last post by:
Hello, I'm building a windows form application in Visual C# using VS 2005. On my form I need to populate a combobox with Invoices# linked to the current reccord's Order# value. This means that: -...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.