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

本文关键字:存储过程 输出 显示 控制台 | 更新日期: 2023-09-27 18:09:31

你好,我在使用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',而没有提供。"如果没有输入,即使假定输出结果,也会得到错误消息。

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

必须像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();