Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hello,

Would like to create a sample C# application with SQL Server 2008 connection.

I have a created a DatabaseTable in SQL 2008 - created and opened a connection using C# Code.

My task is to create a New Record and save it to the SQL 2008 (my DB).

What i would like to know is:

(i) How can i perform this only by using a Stored Procedure

(ii) How to call the Stored Procedure from my code.

Any help regarding this will be appreciated a lot!! Thanks in advance :)
Posted

In your code if you typed your connection string correct the following code should do it;
C#
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) 
{
    CommandType = CommandType.StoredProcedure }) {
    conn.Open();
    command.ExecuteNonQuery();
    conn.Close();
}


If you need to use parameters in your StoredProcedure just add the parameters to the Parameters collection of the SqlCommand object.
Like:
C#
command.Parameters.AddWithValue("paramName", "paramValue");

Good luck,
OI
 
Share this answer
 
v3
Comments
ArunAmalraj 1-Mar-13 4:28am    
Thank you!!
 
Share this answer
 
Comments
ArunAmalraj 1-Mar-13 4:29am    
Thanks you!!
Hi,
Look at this links for creating procedures that are perform crud operations.
1-) http://www.novicksoftware.com/Articles/crud-operations-using-sql-server-stored-procedures-part-2.htm[^]

2-) http://www.pawlowski.cz/2011/01/automating-crud-procedures-generation-t-sql/[^]

And you may call your procedure like this;

C#
using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}



This code is example for calling procedure. You may change paramters for your procedure.

Hope this will help you,
Ibrahim Uylas
 
Share this answer
 
Comments
ArunAmalraj 1-Mar-13 4:29am    
Thank you!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900