SQL 如何合并空字符串和 NULL 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22393182/
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-01 01:21:37  来源:igfitidea点击:

How to COALESCE for empty strings and NULL values?

sqlpostgresqlcoalesce

提问by MikeCW

I'm trying to make the fastest COALESCE() that accepts two or more arguments, and returns the first non-null AND non-empty ("") value.

我正在尝试制作接受两个或更多参数的最快 COALESCE(),并返回第一个非空和非空 ("") 值。

I'm using this:

我正在使用这个:

CREATE OR REPLACE FUNCTION coalescenonempty(VARIADIC in_ordered_actual varchar[])
RETURNS varchar AS $$
  SELECT i
  FROM (SELECT unnest() AS i) t
  WHERE i IS NOT NULL AND i <> ''
  LIMIT 1;
$$ LANGUAGE sql;

It's pretty fast, but still nowhere as fast as COALESCE or CASE WHEN statements.

它非常快,但仍然不如 COALESCE 或 CASE WHEN 语句快。

What do you think?

你怎么认为?

回答by Dwayne Towell

Do not create a user function is you want speed. Instead of this:

不创建用户功能就是要速度。取而代之的是:

coalescenonempty(col1,col2||'blah',col3,'none');

do this:

做这个:

COALESCE(NULLIF(col1,''),NULLIF(col2||'blah',''),NULLIF(col3,''),'none');

That is, for each non-constant parameter, surround the actual parameter with NULLIF( x ,'').

也就是说,对于每个非常量参数,用 将实际参数括起来NULLIF( x ,'')