查询的每个子句的优先级

时间:2011-11-26 15:33:53

标签: sql sql-server sql-server-2008-r2

我正在尝试在SQL Server 2008R2中优先考虑结果,但我没有优先考虑我想要的那些优先级。例如:如果我查询城市,州和邮政编码,并且我有一个邮政编码并且匹配,我希望结果位于顶部。如果拉链不匹配,但城市和州一样,我想在中间这些,那么如果只有国家匹配,结果可以在底部

如果我尝试按表达式的顺序使用LIKE,则查询不会运行。到目前为止,我有:

DECLARE @cityState nvarchar  = 'new york';
DECLARE @zip nvarchar  = '11204';

DECLARE @myposition geography;
SELECT * FROM ZipCodes  z
WHERE Zip LIKE @zip OR (City LIKE @cityState+'%' and State LIKE @cityState+'%' ) 
ORDER BY z.Zip LIKE @zip desc

4 个答案:

答案 0 :(得分:2)

这样的事情怎么样?

SELECT * FROM ZipCodes  z
WHERE Zip LIKE @zip OR (City LIKE @cityState+'%' and State LIKE @cityState+'%' ) 
ORDER BY 
CASE
    WHEN z.Zip LIKE @zip THEN 1
    WHEN City LIKE @cityState+'%' and State LIKE @cityState+'%' THEN 2
    WHEN State LIKE @cityState+'%' THEN 3
    ELSE 4
END,
z.Zip,
City,
State

答案 1 :(得分:0)

尝试:

ORDER BY CASE WHEN Z.ZIP like @zip THEN 1 ELSE 0 END DESC
编辑:由于没有完全阅读这个问题,我的回答是不完整的。来自gpeche的答案更好。

答案 2 :(得分:0)

尝试使用UNION

DECLARE @cityState nvarchar  = 'new york';
DECLARE @zip nvarchar  = '11204';

DECLARE @myposition geography;
SELECT * 
FROM ZipCodes  z
WHERE Zip LIKE @zip

UNION

SELECT * 
FROM ZipCodes  z
City LIKE @cityState+'%' 

UNION

SELECT * 
FROM ZipCodes  z
City LIKE @cityState+'%' 

答案 3 :(得分:0)

谢谢@gpeche。我实际上最终做了一些事情:

  • 声明参数的长度
  • 会计州缩写(纽约与纽约)

导致:

 DECLARE @myposition geography;
 SELECT * FROM ZipCodes  z
 WHERE Zip = @zip OR (City LIKE '%'+@cityState+'%' and ((LEN(@cityState) > 2 AND State LIKE '%'+@cityState+'%' ) OR (State = @cityState))) 

 ORDER BY 
 CASE
    WHEN z.Zip = @zip THEN 1
    WHEN (City LIKE '%'+@cityState+'%' and ((LEN(@cityState) > 2 AND State LIKE '%'+@cityState+'%' ) OR (State = @cityState))) THEN 2
    WHEN State = @cityState+'%' THEN 3
    ELSE 4
 END,z.Zip,City,State