简体   繁体   中英

How to update only first NULL column with a value in Snowflake sql?

How to update a table first Null column with value and other Null columns with the text 'Available'?

My attempt: I tried using Case statements but it is affecting the performance of a query.

Update Emp
SET Level1 = (CASE WHEN Level1 IS NOT NULL THEN Level1 ELSE PermissionCode END), 
    Level2 = (CASE WHEN Level1 IS NOT NULL AND Level2 IS NULL THEN PermissionCode ELSE Level2  END),
  ..and so on

Is there any efficient way to update a table as mentioned below the expected format?

Current Table structure:
========================
| EmpID  | Level1 | Level2 | Level3 | Level4  |....| Level256 | PermissionCode  |
|--------|--------|--------|--------|---------|....|----------|-----------------|        
| 124RY7 | abc    | wsg    | NULL   | NULL    |....|    NULL  |    RT12345      |
| 5T7YTR | efg    | NULL   | NULL   | NULL    |....|    NULL  |    654GTY       |
 

Expected Output:

| EmpID  | Level1 | Level2 | Level3  | Level4  |....| Level256 | PermissionCode  |
|--------|--------|--------|---------|---------|....|----------|-----------------|        
| 124RY7 | abc    | wsg    |RT12345  |Available|....|Available |    RT12345      |
| 5T7YTR | efg    | 654GTY |Available|Available|....|Available |    654GTY       |

  

Try using a combination of nvl2 and coalesce

select empid, lvl1, lvl2, lvl3, lvl4, PC
from temp
union all
select empid, coalesce(lvl1,lvl2,lvl3,lvl4,PC), nvl2(lvl1, coalesce(lvl2,lvl3,lvl4,PC), 'Available'), nvl2(lvl2, coalesce(lvl3,lvl4,PC), 'Available'), nvl2(lvl3, coalesce(lvl4,PC), 'Available')
   , PC
from temp;

在此处输入图片说明

the question is what the actual usecase is. What you can do is try a bulk update (just will have to get autocommit off and commit manually) like "set levelX=Available where levelX-1 is null" for each level for all the columns, which will eventually leave you with just 1 null in every row which you can then fill with the code.

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