开发者

Trying to display output of Stored Procedure in console

Hello I'm having trouble displaying the output of a SP in a console window using C#. Here is the SP code first then the C# after that.

(SP code (Updated with SP code))

- GetDepartmentName stored procedure.
 IF NOT EXISTS (SELECT * FROM sys.objects 
        WHERE object_id = OBJECT_ID(N'[dbo].[GetDepartmentName]') 
        AND type in (N'P', N'PC'))
 BEGIN
 EXEC dbo.sp_executesql @statement = N'
 CREATE PROCEDURE [dbo].[GetDepartmentName]
  @ID int,
  @Name nvarchar(50) OUTPUT
  AS
  SELECT @Name = Name FROM Department
  WHERE DepartmentID = @ID
   '
   END
   GO

(c# code)

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

            int ID = 1;
            //string Name = ""; Tried testing with this 

            try
            {
                conn = new
                SqlConnection("Server=(local);DataBase=School;Integrated Security=SSPI");
                conn.Open();

                SqlCommand cmd = new SqlCommand("GetDepartmentName", conn);

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter("@ID", ID));

                //cmd.Parameters.Add(new SqlParameter("@Name", Name));  Tried testing 
    //with this. Don't get output when added, get error message when commented out.

                rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    Console.WriteLine("Department: {0}", rdr["Name"]);

                }

            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
                if (rdr != null)
                {
                    rdr.Close();
                }
            }
        }

    }


 //cmd.Parameters.Add(new SqlParameter("@Name", Name)); 

I added this line a开发者_开发技巧bove because I keep getting error message ""Procedure or function 'GetDepartmentName' expects parameter '@Name', which was not supplied." Without an input, I get an error message even though this is suppose to output the results..


You have to add that parameter to the command like you did with id

cmd.Parameters.Add(new SqlParameter("@Name"){Direction = Output});

After you execute the command, you can get the value from

cmd.Parameters["@Name"]

Ok try this then

SqlConnection con = new SqlConnection("ConnectionString");
        SqlCommand cmd = new SqlCommand("GetDepartmentName", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = _ID });
        cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar) { Size = 50, Direction = ParameterDirection.Output });
        con.Open();
        cmd.ExecuteNonQuery();

    _Name = cmd.Parameters["@Nume"].Value.ToString();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜