TSQL:向 "SELECT" 结果集添加行

TSQL: Add lines to "SELECT" result set

我们正在使用 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 处添加第二行 "static"。 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 是否有意义?

您需要再添加一个 union :

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

在 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(无论在何处使用此数据)。