如何使用C#将值传递给存储过程

Ani*_*Ani 4 c# stored-procedures

- 存储过程

  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
Run Code Online (Sandbox Code Playgroud)

我在sql server 2005中有这个存储过程,并希望从C#应用程序传递userid.我怎样才能做到这一点.非常感谢.

Ste*_*end 9

MSDN在此广泛介绍了此主题.有关一个很好的示例,请参阅标题为"使用带有SqlCommand和存储过程的参数"一节:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)