简体   繁体   中英

return a default record from a sql query

I have a sql query that I run against a sql server database eg.

SELECT * FROM MyTable WHERE Id = 2

This may return a number of records or may return none. If it returns none, I would like to alter my sql query to return a default record, is this possible and if so, how? If records are returned, the default record should not be returned. I cannot update the data so will need to alter the sql query for this.

Another way (you would get an empty initial rowset returned);

SELECT * FROM MyTable WHERE Id = 2
IF (@@ROWCOUNT = 0)
   SELECT ...

If you have to return whole rows of data (and not just a single column) and you have to create a single SQL query then do this:

Left join actual table to defaults single-row table

select
    coalesce(a.col1, d.col1) as col1,
    coalesce(a.col2, d.col2) as col2,
    ...
from (
    -- your defaults record
    select
        default1 as col1,
        default2 as col2,
        ...) as d
    left join actual as a
    on ((1 = 1) /* or any actual table "where" conditions */)
SELECT TOP 1 * FROM (
SELECT ID,1 as Flag FROM MyTable WHERE Id = 2
UNION ALL
SELECT 1,2
) qry
ORDER BY qry.Flag ASC

You can have a look to this post. It is similar to what you are asking Return a value if no rows are found SQL

I hope that it can guide you to the correct path.

if not exists ( SELECT top 1 * FROM mytable WHERE id = 2 )

select * from mytable where id=  'whatever_the_default_id_is'

else

select * from mytable where id = 2

The query need to return the same number of fields, so you shouldn't do a SELECT * FROM but a SELECT value FROM if you want to return a default value.

With that in mind

SELECT value FROM MyTable WHERE Id = 2
UNION
SELECT CASE (SELECT count(*) FROM MyTable WHERE Id = 2) 
   WHEN 0 THEN 'defaultvalue' 
   END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM