【问题标题】:Creating the temp table to insert the value in the sorting order. It is working fine in SQL Server 2008 but not in SQL Server 2012创建临时表以按排序顺序插入值。它在 SQL Server 2008 中运行良好,但在 SQL Server 2012 中运行良好
【发布时间】:2015-04-19 06:07:33
【问题描述】:

我的确切要求是:我有一个未按顺序排列的Employee 表,所以我想首先按 NM 对其进行排序,然后在表的开头插入一个新行。

Insert into #temptable(ID, name, place,Address) 
   Select 
       ID, name, place, Address 
   from 
       Employee 
   order by 
       NM 

Select 
    0 as ID,
    'Select Employee' as NM,
    'No place' as place,
    'No address' as Address

Union All

Select 
    w.ID, w.NM, w.Place, w.Address 
from 
    #temptable w

我希望联合查询的第二部分由 NM 排序。 上述方法没有按顺序给我结果

建议我使用其他方法,因为这在 SQL Server 2012 中不起作用

【问题讨论】:

  • Define “不工作” - 你是否收到错误 - 如果是,what 错误?你根本没有得到任何结果吗?你得到结果,但没有订购??
  • 选择 0 作为 ID,'Select Employee' 作为 NM,'No place' 作为地方,'No address' 作为地址 Union All SELECT t.* FROM (Select w.ID, w.NM, w.Place, w.Address FROM #temptable w ORDER BY w.NM) t 我尝试了这个查询,它抛出“The Order by Clause 在视图、内联函数、查询中是有效的。请帮助我

标签: sql-server-2012


【解决方案1】:

仅仅因为您按顺序插入它们,并不意味着它们会按顺序出现。如果没有ORDER BY 子句,服务器可以(并且将)以最有效的处理顺序向您返回SELECT。

解决方案: 如果您在查询中添加ORDER BY,您将得到您想要的:

选择 0 作为 ID, '选择员工' 作为 NM, '没有地方'作为地方, “无地址”作为地址 联合所有 选择 t.* 从 (选择 带身份证, w.NM, w.地点, w.地址 从 #诱惑w 订购方式 w.NM) 吨

【讨论】:

  • 我的确切要求是,我有一个未按顺序排列的 Employee 表,
  • 确保结果集按特定顺序返回的唯一方法是使用ORDER BY 子句。
  • 我的确切要求是,我有一个未按顺序排列的 Employee 表,所以我想首先按 NM 排序并在表的开头插入一个新行。插入#temptable(ID,name,place,Address) 选择ID,name,place,Address from Employee order by NM Select 0 as ID,'Select Employee' as NM,'No place' as place,'No address' as Address Union All Select w.ID,w.NM,w.Place,w.Address from #temptable w 我期待结果 NM Select Employee Ab bc cd
  • 您不能将数据库表视为 Excel 工作表。关系数据库基于集合论,其中集合没有顺序。因此,实际表没有顺序的概念,因此确保结果集具有所需顺序的唯一方法是使用ORDER BY 子句。 SQL2008 按您插入的顺序返回结果集的事实纯属巧合。
  • 上述查询将对整体结果应用 order by 子句。有没有一种方法可以让我仅对 Union All 的第二个查询应用 order by 子句????
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 2014-01-12
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多