SQL Server Views with asp.net



我在SQL Server中创建了一个名为view_SelectAll_Student的视图,该视图从单个表名中检索所有列

有一个使用数据适配器返回数据集或数据表的函数,不知何故我收到此错误:

对过程"view_SellectAll_Student"的请求失败,因为"view_SellectAll_Student"是视图对象。

法典:

public DataTable ViewStudentAll() 
{
      cons.Open();
      DataTable dt = new DataTable();
      cmd = new SqlCommand("view_SellectAll_Student", cons);
      cmd.Connection = cons;
      cmd.CommandType = CommandType.StoredProcedure;
      SqlDataAdapter adp = new SqlDataAdapter(cmd);
      adp.Fill(dt);
      cmd.Dispose();
      cons.Close();
      adp.Dispose();
      return dt; 
}

视图仍需要查询。您在这里拥有的只是视图名称。

所以改变这个:

cmd = new SqlCommand("view_SellectAll_Student",cons);

对此:

cmd = new SqlCommand("SELECT put, columns, here FROM view_SellectAll_Student",cons);

确保将视图的列放在那里(或者星号......如果你倾向于这种方式)。

这样写。如果它是一个视图,你应该选择它,否则你不会得到它。

cmd = new SqlCommand("SELECT * FROM view_SellectAll_Student",cons);
cmd.Connection = cons;
//cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
cons.Close();
adp.Dispose();
return dt;

提示:使用DataAdapter时,不需要con.Open()con.Close()语句。 DataAdapter本身将打开和关闭它。

SqlDataAdapter 接受 SqlCommand 作为第一个参数,它可以 是 Select 语句或存储过程。

在这种情况下,您可以将"view_SellectAll_Student"替换为

"Select * from view_SellectAll_Student"
cons.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("select * view_SellectAll_Student",cons);
cmd.Connection = cons;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
cons.Close();
adp.Dispose();
return dt; 

最新更新