2011-01-11 183 views
2

我是新的接口数据库的应用程序,并试图从数据库中我指定的参数应过滤掉结果的几个领域。我一直收到一个没有参数或参数提供。任何人都可以对此有所了解吗?谢谢。通过存储过程传递参数

下面

是存储过程:

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

回答

2

您需要修改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

+0

谢谢。这工作。这是否意味着我在创建S_Proc时使用了DECLARE @UserID,然后在它进入Alter时将其更改为@UserID? – jpavlov 2011-01-11 18:20:01

1
ALTER PROC dbo.PassParamUserID (@UserID int) 

AS 
set nocount on 
SELECT f_Name, l_Name FROM tb_User WHERE tb_User.ID = @UserID; 

如果你想传递参数在您需要的AS语句之前对其进行定义如上所示。