Replacing any NULL fields with a string

筅森魡賤 提交于 2020-01-14 04:07:25

问题


I'm new to SQL and this problem has stumped me. I am supposed to write an SQL statement that lists all the data in a table, but if a column might contain NULL values (in this case only one field is NULL), the phrase "-NONE-" must print in that column for that row. The lab hints that I must use one or more single-row functions to accomplish this.

We are using Oracle SQL Developer to test scripts. I am trying to use the REPLACE function but I keep getting errors. I've tried using NVAL, REPLACE, and other similar functions but I am clearly getting the syntax wrong. For example:

SELECT *, REPLACE(manager_id, NULL, '-NONE-')
FROM departments;

^Always returns an error: missing FROM statement where expected


回答1:


The function you want is coalesce(). This is the ANSI standard function.

Assuming your variable is a character string:

SELECT d.*, COALESCE(manager_id, '-NONE-')
FROM departments d;

If it is not a string, then convert it first:

SELECT d.*, COALESCE(cast(manager_id as varchar(255)), '-NONE-')
FROM departments d;



回答2:


maybe this might help you:

select 
    *, 
    (case when manager_id is null then '-none-' else manager_id end) as manager_id_2
from 
    departments


来源:https://stackoverflow.com/questions/21613714/replacing-any-null-fields-with-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!