繁体   English   中英

使用asp.net的SQL Server视图

[英]SQL Server Views with asp.net

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

我有一个函数可以使用dataadapter返回数据集或数据表,但我却收到此错误:

过程'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; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM