WHERE子句中的SQL if语句

时间:2013-12-24 06:29:53

标签: sql sql-server where-clause

我想做以下查询,我该如何实现呢?

SELECT * FROM table WHERE routeNum LIKE 'N10%' 
-->if no rows return, WHERE clause change to routeName LIKE '&something%'

3 个答案:

答案 0 :(得分:2)

我认为这对你有用:

WITH CTE AS (
    SELECT 2 AS 'INDEX', * FROM table WHERE routeNum LIKE 'N10%'
    UNION ALL
    SELECT 1 AS 'INDEX', * FROM table WHERE routeNum LIKE '&something%'
)
SELECT *
FROM CTE
WHERE CTE.INDEX = (SELECT MAX(INDEX) FROM CTE)

由于您必须在两个结果集之间进行选择,您将需要两个查询,这两个查询将返回两个不同的集合,然后根据与已运行的查询对应的“索引”,您选择如何显示结果

这是SQLFiddle演示。

答案 1 :(得分:1)

可能的解决方案

WITH cte AS 
(
  SELECT * 
    FROM routes 
   WHERE routeNum LIKE 'N10%'
)
SELECT * FROM cte
UNION ALL
SELECT * FROM routes 
 WHERE routeNum LIKE 'something else%'
   AND NOT EXISTS
(
  SELECT * 
    FROM cte
)

这是 SQLFiddle 演示

答案 2 :(得分:0)

WITH tmp AS
(
SELECT t.*, 
CASE 
    WHEN routeNum LIKE 'N10%' THEN 1 
    WHEN routeNum LIKE '&something%' THEN 2
    ELSE 3 END AS q
FROM table t
)

SELECT * FROM tmp t
WHERE q = CASE WHEN (SELECT COUNT(*) FROM tmp WHERE q = 1 ) > 0 THEN 1 ELSE 2 END