【问题标题】:SQL Server 2000: select into case when in order by clauseSQL Server 2000:在 order by 子句中选择大小写
【发布时间】:2012-08-02 14:57:14
【问题描述】:

我正在尝试在 ORDER BY 子句中使用 CASE 语句将行选择到临时表中,但插入时未对记录进行排序。

Declare @orderby varchar(10) , @direction varchar(10)
set @orderby = 'col1'
set @direction = 'desc'
select identity (int) as autoid, *
into #temp
from table 
order by case when @direction = 'desc' and @orderby = 'co1' then col1 end desc

declare @startrow int
declare @maxrows int
set @starrow = 19
set @maxrow = 30
set rowcount @maxrows
select * from #temp 
where autoid > @startrow

【问题讨论】:

  • 尝试以特定顺序插入临时表绝对没有意义 - 当您希望以特定顺序返回行时,无论如何您都需要特定的 ORDER BY .....那么你到底想达到什么目的呢?
  • 我想将此查询用于分页。我将从我的临时表中进行选择,并且我需要按作为参数传入的列对 autoid 进行排序。我编辑了我的问题以获得我的最终选择语句。
  • 您可以从原始数据中执行此操作 - 使用 CTE 和 ROW_NUMBER() - 无需先将这些内容放入单独的临时表中,只需进行分页.....
  • 我正在使用没有函数 row_number 的 sql server 2000
  • 我也在从长查询中进行选择。我只使用表格发布了问题,因为我认为没有必要在此处进行整个查询。基本上我的问题是:有什么方法可以有条件地选择临时表排序???

标签: tsql sql-server-2000 temp case-statement select-into


【解决方案1】:

最坏的情况 - 您只需要使用两个单独的 SQL 查询来实现您的目标:

if @direction = 'desc'
  select identity (int) as autoid, *
  into #temp
  from table 
  order by col1 desc

if @direction = 'asc'
  select identity (int) as autoid, *
  into #temp
  from table 
  order by col1 asc

【讨论】:

  • 临时表可以按六列排序,每列可以按asc或desc排序。我想我不想写12个单独的查询。
【解决方案2】:

您需要在 order by 子句中使用多个排序条件才能正确处理此问题。这种方法的问题是,当表中有很多行时,性能会很差,因为这种讨厌的排序操作。

相反,您最好使用动态 SQL(正如其他人建议的那样)。

Declare @orderby varchar(100) , @direction varchar(10)
set @orderby = 'col1'
set @direction = 'desc'
select identity (int) as autoid, *
into #temp
from table 
order by case when @direction = 'desc' and @orderby = 'col1' then col1 end desc,
         case when @direction = 'asc'  and @orderby = 'col1' then col1 end,
         case when @direction = 'desc' and @orderby = 'col2' then col2 end desc,
         case when @direction = 'asc'  and @orderby = 'col2' then col2 end,
         case when @direction = 'desc' and @orderby = 'col3' then col3 end desc,
         case when @direction = 'asc'  and @orderby = 'col3' then col3 end,
         case when @direction = 'desc' and @orderby = 'col4' then col4 end desc,
         case when @direction = 'asc'  and @orderby = 'col4' then col4 end,
         case when @direction = 'desc' and @orderby = 'col5' then col5 end desc,
         case when @direction = 'asc'  and @orderby = 'col5' then col5 end

【讨论】:

    【解决方案3】:

    您可以不使用 #temp 表 insted 使用普通表临时来实现此目的。稍后当您完成您的流程时,您可以将其放在最后。

    declare @dir varchar(10)='desc'
    DECLARE @str varchar(1000)
    SET @str='select identity (int) as autoid,
    * into temp from cust1 order by TransactionType '+@dir 
    exec(@str)
    select * from temp
    

    【讨论】:

    • 因为他使用 SQL Server 2000,所以这不是一个有效的选项(见最后一条评论)
    • 哦,是的,我没有看到他的最后评论。我会在 sql 2000 中得到这个
    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多