Search code examples
sql-servert-sqlsqlxml

TSQL: How to ouput records even when where condition doesnt match


I have a temp table with 3 columns "ID","Cost", "MaxCost"..below is my select statement which selects rows given particular ID..

        SELECT
            t.Cost 
            t.MaxCost
        FROM @temp t
        WHERE t.ID = @ID        

How do i modify the above query so that even if given ID doesn't exists it still output rows with Cost = 0 & MaxCost = 0


Solution

  • Select both the actual and the default record, and select the first one ordering by their weight.

    select top (1)
      Cost,
      MaxCost
    from (
      SELECT
        t.Cost 
        t.MaxCost,
        1 as takeme
      FROM @temp t
      WHERE t.ID = @ID
    
      union all
    
      select 0, 0, 0
    ) foo
    order by
      foo.takeme desc