How to set a default row for a query that returns no rows?

后端 未结 11 1466
青春惊慌失措
青春惊慌失措 2020-12-03 06:43

I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I\'m only returning a single column from this particular table

11条回答
  •  盖世英雄少女心
    2020-12-03 07:08

    This snippet uses Common Table Expressions to reduce redundant code and to improve readability. It is a variation of John Baughman's answer.

    The syntax is for SQL Server.

    WITH products AS (
                SELECT prod_name,
                       price
                  FROM Products_Table
                 WHERE prod_name LIKE '%foo%'
         ),
         defaults AS (
                SELECT '-' AS prod_name,
                       0   AS price
         )
    
    SELECT * FROM products
    UNION ALL
    SELECT * FROM defaults
     WHERE NOT EXISTS ( SELECT * FROM products );
    

提交回复
热议问题