简体   繁体   中英

SQL DB2 Replace value in a column

I have the following column, B represents boolean and the rest are empty values. I have to change all the values in this column to the word COLUMN A.

  COLUMN
  -----


   B

I have tried different things, for example

 SELECT COLUMN 
 FROM TABLE
 WHERE COALESCE(NULLIF(COLUMN,''), 'COLUMN A');

And I receive the error: "Invalid character found in a character string argument of the function "BOOLEAN"." I'm kind of stuck to this question and I'm getting confused with this boolean value. I will be really happy if someone can help me, thanks!

The WHERE clause is unfinished. Compare the COALESCEd value to something:

SELECT COLUMN 
 FROM TABLE
 WHERE COALESCE(NULLIF(COLUMN,''), 'COLUMN A') = 'COLUMN A';

Or better:

SELECT COLUMN 
 FROM TABLE
 WHERE COLUMN IS NULL OR COLUMN = ''

Doesn't require any thinking/calculating to work out your selection logic. More maintainable, nicer for peer developers

*The above is generic advice for usual cases NOT involving boolean datatypes (which typically require some different treatment)


Now, you say you have to change the value to something. That requires an UPDATE statement. If this column is a boolean then it won't have a value of empty string. The blanks will be nulls:

UPDATE TABLE SET COLUMN = (some boolean) WHERE COLUMN IS NULL

If you don't want to permanently change the table data to something, but instead want to select it out as some value where a blank occurs, but keep the blanks stored in the table:

SELECT COALESCE(column, (some boolean)) FROM TABLE

Might be worth noting that not all versions of DB2 can return a boolean in a result set - this is quite typical of database vendors. Convert the boolean to something else representable using a case when, if your DB2 version is thus restricted

SELECT CASE WHEN column = TRUE THEN 'true' ELSE 'false' END FROM TABLE

The easiest thing is to use CASE expression. I am not familiar in db2, so you may want to research it further, but in other DBMSs it works like this:

SELECT CASE WHEN COLUMN = '' THEN 'COLUMN A' -- if COLUMN = '', replace it with 'COLUMN A' ELSE COLUMN -- otherwise, keep COLUMN as is. END as 'COLUMN' -- name the column in the result 'COLUMN' FROM TABLE

This is an article that explains how it works in db2: https://www.ibm.com/support/knowledgecenter/en/SSEPEK_11.0.0/sqlref/src/tpc/db2z_caseexpression.html

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