--存储过程
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/