简体   繁体   中英

Why is CASE - WHEN - ELSE not working for me in pgadmin in this once instance?

Working with postgres 9.4 and using PGAdmin III: I have a schema with a character field that MAY contain "new lines" (NLs), or MAY contain double spaces, or neither. I need to divide the field into 3 segments by either of the above factors or by 26 characters in length.

If the total length is 26 or less, I just copy it as is. If it has NLs, then I split it by those. If no NLs but it has double spaces, I split it by those. Finally, if none of the above, I want to split it into 3 26 character chunks.

For context; the column is data entered by customers into a 3 line box. anywhere from 4 characters up to 78. Some use NLs, some use spaces to push the text to the next line, some have luck with spacing so use neither.

Here's the part of the query to gather the first line:

CASE WHEN LENGTH(detail) < 27 THEN detail
     WHEN detail LIKE E'%\n%' THEN SPLIT_PART(detail,E'\n',1)
     WHEN detail LIKE E'%  %' THEN SPLIT_PART(detail,E'  ',1)
     ELSE LEFT(detail, 26)
END AS line1, 

When I test this on a sample schema, the first three parts work exactly as I need but the "ELSE" part never does. The LEFT statement workout outside of the CASE statement but not within.

I've tried enclosing it with a SELECT clause, nesting several CASE-WHEN-ELSE statements, and other things to no avail.

Oddly, it DOES work if I take out the "SPLIT_PART" line referring to '% %'.

Short of giving up on the double-space split, is there another solution, or have I just formatted something wrong?

CASE WHEN LENGTH(detail) < 27 THEN detail
     WHEN detail LIKE '%\n%' THEN  SPLIT_PART(detail,'\n',1)
     WHEN  position(' ' in detail) > 0 THEN SPLIT_PART(detail,' ',1)
     ELSE left(detail,26)

After another bit of time mucking about, I suspected the LIKE E'% %' might be the issue - and it was. Simply changing it to LIKE E' ' allows it to work like I wanted.

Added: Turns out the best solution is a combination of "position" to determine if the double space exists, and split-part to separate correctly at the location.

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-2025 STACKOOM.COM