尝试在控制台中显示存储过程的输出

时间:2011-09-25 16:12:24

标签: c# stored-procedures

您好我在使用C#在控制台窗口中显示SP的输出时遇到问题。首先是SP代码,然后是C#。

(SP代码(使用SP代码更新))

- 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#代码)

     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)); 

我在上面添加了这一行,因为我不断收到错误消息“”过程或函数'GetDepartmentName'需要参数'@Name',这是未提供的。“没有输入,我收到一条错误消息,即使这是假设输出结果..

1 个答案:

答案 0 :(得分:2)

您必须像使用id

一样将该参数添加到命令中
cmd.Parameters.Add(new SqlParameter("@Name"){Direction = Output});

执行命令后,您可以从

获取值
cmd.Parameters["@Name"]

好的,试试这个

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();