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

标签 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

我在 sql server 2005 中有这个存储过程,想从 C# 应用程序传递用户标识。我怎样才能做到这一点。非常感谢。

最佳答案

MSDN here 中广泛介绍了该主题.请参阅标题为“将参数与 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();
    }
}

关于c# - 如何使用 C# 将值传递给存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3806229/

相关文章:

c# - 如何对邮件发送功能进行单元测试

c# - 使用 Selenium WebDriver.dll 的 Azure 函数

c# - 在 .NET C# 项目中使用 PHP

mysql - 如何创建接受用户 ID 并返回用户全名和职业以及 1 个电子邮件地址的存储过程

sql - 跨不同环境查询存储过程中的多个数据库的最佳方法是什么

c# - 使用具有用户名密码身份验证的smtp服务器发送电子邮件C#

c# - 仅在 Visual Studio 2015 中的 Debug模式下抛出 WebDriverWait 异常

MySQL innodb 过程在事务中仅事件一次(调用多次)

mysql - 如何使用存储过程和条件获取数据库表结果?

mysql - 存储过程 - 错误 #1064