开发者

Passing Parameters through stored Procedure

I am new to interfacing DB's with applications and am trying to pull a couple of fields from a database where the parameter I specified should filter out the results. I keep receiving a no parameters or arguments were supplied. Can anyone shed a little insight on this? Thanks.

below is the stored procedure:

ALTER PROC dbo.PassParamUserID

AS
set nocount on
DECLARE @UserID int;

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

And here is my code

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开发者_如何学Python 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"]);
            }
        }


You need to modify your SQL stored proc to:

ALTER PROC dbo.PassParamUserID

@UserID int

AS set nocount on

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

At the moment you are just declaring it as a variable within the procedure.

Here are some MSDN articles that may help you going forward:

Creating and Altering Stored procedures

Declaring Local Variables


ALTER PROC dbo.PassParamUserID (@UserID int)

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

If you want to pass a parameter in you need to define it before the AS statement as shown above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜