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

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

提交回复
热议问题