使用其他表创建一个新表

时间:2017-06-02 13:42:31

标签: c# sql asp.net database

当我进行查询时

SELECT a.ID, 
       a.Employee, 
       b.Name, 
       b.[Open Date] 
  FROM tblEmployees a, 
       Stores b

效果很好,但是当我查询时

SELECT a.ID, 
       a.Employee, 
       b.Name, 
       b.[Open Date], 
       c.Task 
  FROM tblEmployees a, 
       Stores b, 
       tblTasks c

它不起作用。

它一直在sda.Fill(dt)上发出错误:

  

System.OutOfMemoryException:'System.OutOfMemoryException'

private DataTable GetData() 
{
    string connString = @"Data Source=aa.database.windows.net;Initial Catalog=aa;Persist Security Info=True;User ID=aa;Password=aa";
    string query = "SELECT a.ID, a.Employee, b.Name, b.[Open Date], c.Task FROM tblEmployees a, Stores b, tblTasks c";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

所有表格中的数据是否已关联?如果是这样,您必须使用连接语句

显式化此链接
SELECT a.ID, 
       a.Employee, 
       b.Name, 
       b.[Open Date], 
       c.Task 
  FROM tblEmployees a
  JOIN Stores b on b.id = a.id_store -- explicit our link here
  JOIN Tasks c on c.id = a.id_task -- explicit our link here

但是如果你试图从3个不同的表中请求数据,那么最好做3个请求

答案 1 :(得分:0)

或者,您可以在where子句中进行连接:

SELECT a.ID, 
       a.Employee, 
       b.Name, 
       b.[Open Date], 
       c.Task 
  FROM tblEmployees a, 
       Stores b, 
       tblTasks c
  where a.id = b.employeeid  -- clearly made up these name
  and  c.taskownerid= a.id
顺便说一下,这个问题的标题似乎与实际要求大不相同。