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

后端 未结 11 1426
青春惊慌失措
青春惊慌失措 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:06

    Do you want to return a full row? Does the default row need to have default values or can it be an empty row? Do you want the default row to have the same column structure as the table in question?

    Depending on your requirements, you might do something like this:

    1) run the query and put results in a temp table (or table variable) 2) check to see if the temp table has results 3) if not, return an empty row by performing a select statement similar to this (in SQL Server):

    select '' as columnA, '' as columnB, '' as columnC from #tempTable
    

    Where columnA, columnB and columnC are your actual column names.

    0 讨论(0)
  • 2020-12-03 07:07

    Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable.

        ---=== The table & its data
        CREATE TABLE dbo.Rates (
            PkId int,
            name varchar(10),
            rate decimal(10,2)
        )
        INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1)
        INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2)
    

    Here's the solution:

    ---=== The solution 
    CREATE PROCEDURE dbo.GetRate 
      @PkId int
    AS
    BEGIN
      DECLARE @tempTable TABLE (
        PkId int, 
        name varchar(10), 
        rate decimal(10,2)
     )
    
     --- [1] Insert default values into @tempTable. PkId=0 is dummy value  
     INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00)
    
     --- [2] Update the single row in @tempTable with the actual value.
     ---     This only happens if a match is found
     UPDATE @tempTable
        SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate
        FROM @tempTable t INNER JOIN dbo.Rates x
        ON t.PkId = 0
        WHERE x.PkId = @PkId
    
     SELECT * FROM @tempTable
    END
    

    Test the code:

    EXEC dbo.GetRate @PkId=1     --- returns values for PkId=1
    EXEC dbo.GetRate @PkId=12314 --- returns default values
    
    0 讨论(0)
  • 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 );
    
    0 讨论(0)
  • 2020-12-03 07:15

    *SQL solution

    Suppose you have a review table which has primary key "id".

    SELECT * FROM review WHERE id = 1555
    UNION ALL
    SELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1
    

    if table doesn't have review with 1555 id then this query will provide a review of id 1.

    0 讨论(0)
  • 2020-12-03 07:16

    Assuming there is a table config with unique index on config_code column:

    CONFIG_CODE     PARAM1   PARAM2
    --------------- -------- --------
    default_config  def      000
    config1         abc      123
    config2         def      456
    

    This query returns line for config1 values, because it exists in the table:

    SELECT *
      FROM (SELECT *
              FROM config
             WHERE config_code = 'config1'
                OR config_code = 'default_config'
             ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
     WHERE rownum = 1;
    
    CONFIG_CODE     PARAM1   PARAM2
    --------------- -------- --------
    config1         abc      123
    

    This one returns default record as config3 doesn't exist in the table:

    SELECT *
      FROM (SELECT *
              FROM config
             WHERE config_code = 'config3'
                OR config_code = 'default_config'
             ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
     WHERE rownum = 1;
    
    CONFIG_CODE     PARAM1   PARAM2
    --------------- -------- --------
    default_config  def      000
    

    In comparison with other solutions this one queries table config only once.

    0 讨论(0)
提交回复
热议问题