c# - 通过存储过程传递参数

标签 c# t-sql stored-procedures

我是数据库与应用程序接口(interface)的新手,并且正在尝试从数据库中提取几个字段,其中我指定的参数应该过滤掉结果。我不断收到没有提供参数或参数的消息。谁能对此有所了解?谢谢。

下面是存储过程:

ALTER PROC dbo.PassParamUserID

AS
set nocount on
DECLARE @UserID int;

SELECT f_Name, l_Name
FROM tb_User
WHERE tb_User.ID = @UserID;

这是我的代码

class StoredProcedureDemo
{
    static void Main()
    {
        StoredProcedureDemo spd = new StoredProcedureDemo();

        //run a simple stored procedure that takes a parameter
        spd.RunStoredProcParams();
    }

    public void RunStoredProcParams()
    {
        SqlConnection conn = null;
        SqlDataReader rdr = null;

        string ID = "2";

        Console.WriteLine("\n the customer full name is:");

        try
        {
            //create a new connection object
            conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
            conn.Open();

            //create command objects identifying the stored procedure
            SqlCommand cmd = new SqlCommand("PassParamUserID", conn);

            //Set the command object so it know to execute the stored procedure
            cmd.CommandType = CommandType.StoredProcedure;

            //ADD PARAMETERS TO COMMAND WHICH WILL BE PASSED TO STORED PROCEDURE
            cmd.Parameters.Add(new SqlParameter("@UserID", 2));

            //execute the command
            rdr = cmd.ExecuteReader();

            //iterate through results, printing each to console
            while (rdr.Read())
            {
                Console.WriteLine("First Name: {0,25} Last Name: {0,20}", rdr["f_Name"], rdr["l_Name"]);
            }
        }

最佳答案

您需要将 SQL 存储过程修改为:

ALTER PROC dbo.PassParamUserID

@UserID int

AS set nocount on

SELECT f_Name, l_Name FROM tb_User WHERE tb_User.ID = @UserID;

目前您只需将其声明为过程中的变量。

以下一些 MSDN 文章可能会帮助您继续前进:

Creating and Altering Stored procedures

Declaring Local Variables

关于c# - 通过存储过程传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661058/

相关文章:

mysql - 使用存储过程解决的具有挑战性的现实示例或情况的示例

sql-server - 检查记录是否存在,如果是,则“更新”,如果不是,则“插入”

c# - 外部身份验证后如何从用户那里收集更多信息?

c# - MVC4 - 在 DropDownList 中设置初始选定的项目

sql - 按数字顺序排列字符串 alpha A1-1-1、A1-2-1、A1-10-1、A1-2-2、A1-2-3 等

sql - 有条件求和

mysql - 为什么这个基于 CASE 的更新会导致复制偏差?

c# - 为什么 OrdinalIgnoreCase 和 InvariantCultureIgnoreCase 返回不同的结果?

c# - 是否可以创建一个由其他属性组合而成的类属性?

.net - 按多列排序