oracle 在 select 语句中设置默认值(不使用 UNION 语句)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16028352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 01:34:43  来源:igfitidea点击:

Set default value in select statement(not use UNION statement)

mysqlsqlsql-serveroracledb2

提问by Rong Nguyen

I would like to have a SELECT statement that will return specified default values if no rows are returned from the database.

我想要一个 SELECT 语句,如果没有从数据库返回行,它将返回指定的默认值。

We can use UNION to get the desired result like this question: "How to set a default row for a query that returns no rows?", but this gives an extra result row.

我们可以使用 UNION 来获得所需的结果,如以下问题:“如何为不返回行的查询设置默认行?”,但这会提供额外的结果行。

example:

例子:

SELECT a 
    from TBL_TEST 
UNION 
SELECT 0 
    FROM DUAL

Is there a better way, or a standard SQL way to do this that will be portable across multiple database engines?

有没有更好的方法,或者标准的 SQL 方法来做到这一点,可以跨多个数据库引擎移植?

回答by faisal

SELECT ifnull(a,20) FROM TBL_TEST 

Selects 20 if a is null otherwise selects a (in mysql, not sure about others)

如果 a 为空,则选择 20 否则选择 a(在 mysql 中,不确定其他人)

回答by WarrenT

For a portable solution, how about:

对于便携式解决方案,如何:

select coalesce(a, 0)
    from TBL_TEST 
    right outer join DUAL on null is null

The COALESCE function is used here because it is more portable than NVL() or IFNULL().

此处使用 COALESCE 函数是因为它比 NVL() 或 IFNULL() 更具可移植性。

You would have a DUAL table created in database systems that use a different name, such as SQL Server or DB2.

您将在使用不同名称的数据库系统(例如 SQL Server 或 DB2)中创建一个 DUAL 表。

回答by tadman

MySQL has the DEFAULTfunction, but I'm not sure how standard or widely supported it is.

MySQL 具有该DEFAULT功能,但我不确定它的标准或广泛支持程度。

回答by Vijendra Singh

MySQL IFNULL is like oracle's NVL function 
MySQL IFNULL() takes two expressions and if the first expression is not NULL, it returns the first expression. Otherwise it returns the second expression.
Syntax 

IFNULL(expression1, expression2); 

SELECT IFNULL(a,<default value>) from TBL_TEST 

回答by Egor Skriptunoff

In Oracle:

在甲骨文中:

select nvl(a, 0)
from DUAL left join TBL_TEST on null is null

回答by Anvesh

In, SQL SERVER 2008 R2 : When Value IS NULL

在 SQL SERVER 2008 R2 中:当值为 NULL 时

SELECT ISNULL(a,<Default Value>) from TBL_TEST

e.g. SELECT ISNULL(a,0) from TBL_TEST

回答by MGPJ

use the COALESCE() to convert the null value column with its default value such as

使用 COALESCE() 将空值列转换为其默认值,例如

select coalesce(a,0) from TBL_TEST

从 TBL_TEST 中选择合并 (a,0)

回答by Anvesh

In, SQL SERVER 2008 R2 : When Empty String

在 SQL SERVER 2008 R2 中:当为空字符串时

SELECT ISNULL(NULLIF(a,<Empty String>)<Default Value>) from TBL_TEST

e.g. SELECT ISNULL(NULLIF(a,'')0) from TBL_TEST

This is working fine...

这工作正常...