Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value to a stored procedure using C#

--Stored procedure

  ALTER PROCEDURE [dbo].[Test]             
@USERID varchar(25)              

 AS               
 BEGIN                  
SET NOCOUNT ON                    
IF NOT EXISTS Select * from Users where USERID = @USERID)         
    BEGIN                          
        INSERT INTO Users (USERID,HOURS) Values(@USERID, 0);                   
    END

I have this stored procedure in sql server 2005 and want to pass userid from a C# application. How can I do that. Many Thanks.

like image 419
Ani Avatar asked Jan 22 '23 09:01

Ani


1 Answers

This topic is extensively covered in MSDN here. See the section entitled "Using Parameters with a SqlCommand and a Stored Procedure" for a nice sample:

static void GetSalesByCategory(string connectionString, 
    string categoryName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "SalesByCategory";
        command.CommandType = CommandType.StoredProcedure;

        // Add the input parameter and set its properties.
        SqlParameter parameter = new SqlParameter();
        parameter.ParameterName = "@CategoryName";
        parameter.SqlDbType = SqlDbType.NVarChar;
        parameter.Direction = ParameterDirection.Input;
        parameter.Value = categoryName;

        // Add the parameter to the Parameters collection. 
        command.Parameters.Add(parameter);

        // Open the connection and execute the reader.
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
    }
}
like image 73
Steve Townsend Avatar answered Jan 29 '23 15:01

Steve Townsend