TSQL:将行添加到“ SELECT”结果集中

时间:2018-08-08 13:52:19

标签: sql sql-server tsql sql-server-2017-express

我们正在使用SQL Server 2017 Express,并且我有以下SELECT语句:

SELECT * FROM 
(SELECT '' as ItemId, '-- Please select --' as ItemDesc
    UNION 
    SELECT [id] as ItemId, [DisplayName] as ItemDesc 
    FROM [table] 
) as t
ORDER BY
CASE ItemDesc
    when '-- Please select --' then 1
    when 'bla' then 2
    when 'fasel' then 3
    when 'blubb' then 4
    when 'lala' then 5
    when 'duh!' then 6
    when 'spamalot' then 7
    else 8
end, ItemDesc

这可行,但是我需要在pos处添加第二条“静态”行。 8,类似

SELECT * FROM 
    (SELECT '' as ItemId, '-- Please select --' as ItemDesc,
     '' as ItemId, '----------' as ItemDesc
        UNION 
    ...
CASE ItemDesc
    ...
        when '----------' then 8
        else 9

这当然是行不通的,但是您知道了。不幸的是,我无权访问创建列表的代码,我所能做的就是将Javascript添加到输出中。

这有可能吗?并且不使用JS来操作DOM并有意义吗?

2 个答案:

答案 0 :(得分:0)

您需要再添加一个union

SELECT t.*
FROM (SELECT '' as ItemId, '-- Please select --' as ItemDesc
      UNION 
      SELECT '', '----------' 
      UNION
      SELECT [id] , [DisplayName] 
      FROM [table] 
     ) t
ORDER BY . . . ;

答案 1 :(得分:0)

将新列添加到UNION中的每个SELECT中,从而确定排序顺序,因此您不必费心使用CASE:

SELECT itemid, ItemDesc FROM 
(
    SELECT '' as ItemId, '-- Please select --' as ItemDesc, 0 as mysortcolumn
    UNION 
    SELECT 
        [id] as ItemId, 
        [DisplayName] as ItemDesc, 
        CASE ItemDesc           
            when 'bla' then 1
            when 'fasel' then 2
            when 'blubb' then 3
            when 'lala' then 4
            when 'duh!' then 5
            when 'spamalot' then 6
            else 7 END as mysortcolumn 
    FROM [table] 
    UNION 
    SELECT '' as ItemId, '-- Please select --' as ItemDesc, 1000 as mysortcolumn
) as t
ORDER BY mysortcolumn asc;

但是...感觉就像您正在尝试在记录集中构建UI。您确定这是应该执行此逻辑的地方吗?对于数据库来说非常麻烦。感觉好像您应该针对SELECT运行一个[table]的语句,并按顺序执行,然后应该由构建UI的代码编写两条开始和结束行(无论在何处使用此数据) )。