简体   繁体   English

从sql查询返回默认记录

[英]return a default record from a sql query

I have a sql query that I run against a sql server database eg. 我有一个sql查询,我对SQL服务器数据库运行,例如。

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? 如果它没有返回,我想改变我的sql查询以返回默认记录,这是可能的,如果是这样,怎么样? 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. 我无法更新数据,因此需要更改sql查询。

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: 如果必须返回整行数据(而不仅仅是单个列),则必须创建单个SQL查询,然后执行以下操作:

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 它与您要求的类似。 如果没有找到行SQL,则返回一个值

I hope that it can guide you to the correct path. 我希望它可以引导你走正确的道路。

if not exists ( SELECT top 1 * FROM mytable WHERE id = 2 ) 如果不存在( 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. 查询需要返回相同数量的字段,因此如果要返回默认值,则不应执行SELECT * FROM而应使用SELECT value FROM

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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