2016-09-22 87 views
0

我使用以下查询来填充业务目录表结果的下拉字段。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 

我想保持我在列表顶部的“选择一个城市”,而不是把它按字母顺序排列,但保持一切相同。

这可能吗?

+2

请注意,请考虑接受对您以前的问题的正确答案....它鼓励其他人帮助你。干杯。 http://stackoverflow.com/questions/39626354/order-by-select-statement-using-union-distinct http://stackoverflow.com/questions/39624368/t-sql-query-to-search-table领域的关键字 http://stackoverflow.com/questions/39542201/sql-split-string-as-key-identity-value 等... – scsimon

+0

你好@scsimon是的,我要回答这些现在的主题。我最终使用原始查询,因为插件端存在一个错误,所以输入值得高度赞赏,但在一天结束时,我终于坚持原始查询,并且我无法在同一天回答自己的问题。 – UserSN

+0

听起来不错Alex。 – scsimon

回答

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 
+0

给我错误消息:如果语句包含UNION,INTERSECT或EXCEPT运算符,则ORDER BY项必须出现在选择列表中。 – UserSN

+1

@AlexP将其包装在CTE中以使其更容易 – scsimon

+0

谢谢@scsimon这个作品!我将读到关于“包装”的概念,我看到它经常使用和cte。我还是个新手,需要更长的时间才能理解什么让事情成功而不是。 – UserSN

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; 

前提是你对城市的指数,你会得到你的结果,而不排序(我用我的DDL的UNIQUE约束创建一个)在执行计划中。

+0

感谢你的例子。以前的答案让它为我工作。我将不得不阅读一些关于索引的内容,以及它们可以用来做什么。我目前正在寻找一些关于国家/国家的索引,因为就目前而言,我从scsimon使用的查询正在将数据输入到我的BND_Listing表中。但我存储的国家缩写同样适用于国家,我想将这些缩写显示为完整的州/国家/地区。感谢您的回答! – UserSN