【问题标题】:Passing Parameters through stored Procedure通过存储过程传递参数
【发布时间】:2011-01-11 18:14:17
【问题描述】:

我是连接数据库与应用程序的新手,我正在尝试从数据库中提取几个字段,我指定的参数应该过滤掉结果。我一直收到没有提供参数或参数的消息。任何人都可以对此有所了解吗?谢谢。

下面是存储过程:

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"]);
            }
        }

【问题讨论】:

    标签: c# tsql stored-procedures


    【解决方案1】:

    您需要将您的 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

    【讨论】:

    • 谢谢。那行得通。这是否意味着我在创建 S_Proc 时使用 DECLARE @UserID,然后在转到 Alter 时将其更改为 @UserID?
    • 不,您在创建和更改过程的 AS 语句之前定义参数。我在我的回答中添加了一些 MSDN 文章的链接。
    • @japlov。 Declare 以与 string ID = "2"; 相同的方式定义局部变量。 ALTER PROC dbo.PassParamUserID @UserID int 以与 RunStoredProcParams(string ID) 相同的方式使其成为参数。 Alter 是因为你需要改变,没有其他原因
    【解决方案2】:
    ALTER PROC dbo.PassParamUserID (@UserID int)
    
    AS 
    set nocount on 
    SELECT f_Name, l_Name FROM tb_User WHERE tb_User.ID = @UserID;
    

    如果要传入参数,需要在AS语句之前定义好,如上图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2016-04-05
      • 1970-01-01
      • 2021-04-28
      相关资源
      最近更新 更多