tsql填充的下拉列表保持默认选项在顶部

时间:2016-09-22 18:34:18

标签: tsql

我使用以下查询使用业务目录表中的结果填充下拉字段。

select 'Select a City' as City, 'All' as Value
UNION ALL
select distinct City, City as Value from BND_Listing
where isnull(City,'') <> ''
Order by City ASC

我想保留我的选择城市&#39;在列表的顶部,并没有按字母顺序排序,但保持其他一切。

这可能吗?

2 个答案:

答案 0 :(得分:1)

with cte as(
select 'Select a City' as City, 'All' as Value
UNION ALL
select distinct City, City as Value from BND_Listing
where isnull(City,'') <> '')


select * from cte  Order by case when City = 'Select a City' then 1 else 2 end, City ASC

答案 1 :(得分:1)

另一种解决方法是:

-- sample data
DECLARE @BND_Listing TABLE (City varchar(100) UNIQUE);
INSERT @BND_Listing VALUES ('Chicago'),('New York'),('LA');

-- solution
SELECT City, Value
FROM
(
  SELECT 0 as oGroup, 'Select a City' as City, 'All' as Value
  UNION ALL
  SELECT DISTINCT 1, City, City FROM @BND_Listing
  WHERE City IS NOT NULL AND City <> ''
) prep
ORDER BY oGroup;

如果您在City上有一个索引(我在我的DDL中使用UNIQUE约束创建了一个索引),您将在执行计划中获得没有排序的结果。