是否存在替代CASE的函数,可为非有效数字字符串返回默认值?
Hey there! Great question—let’s break this down for you. There isn’t a universal "NVL-like" function that directly handles this custom valid number rule out of the box, but most databases have built-in tools to avoid writing overly verbose CASE statements. Let’s cover solutions for common databases based on your specific requirements (allowing commas, blocking any alphabetic characters including e):
First, let’s clarify your valid number definition from the example: strings are valid only if they contain only digits and commas—any letters (like A, B, C, e) make them invalid, which should return 0.
Oracle
You can combine REGEXP_LIKE with either CASE or NVL2 for a clean solution:
SELECT CASE WHEN REGEXP_LIKE(EMPNO, '^[0-9,]+$') THEN EMPNO ELSE '0' END AS cleaned_empno FROM your_table;
Or simplify with NVL2 (same logic, shorter syntax):
SELECT NVL2(REGEXP_LIKE(EMPNO, '^[0-9,]+$'), EMPNO, '0') AS cleaned_empno FROM your_table;
The regex ^[0-9,]+$ ensures the string only includes digits and commas. Any letters will fail the match, triggering the 0 default.
SQL Server
Use PATINDEX to detect non-valid characters (anything that’s not a digit or comma):
SELECT CASE WHEN PATINDEX('%[^0-9,]%', EMPNO) = 0 THEN EMPNO ELSE '0' END AS cleaned_empno FROM your_table;
PATINDEX('%[^0-9,]%', EMPNO) returns the position of the first non-digit/comma character. A result of 0 means no invalid characters exist.
PostgreSQL
Leverage PostgreSQL’s regex matching operator ~ with a CASE statement:
SELECT CASE WHEN EMPNO ~ '^[0-9,]+$' THEN EMPNO ELSE '0' END AS cleaned_empno FROM your_table;
You can also use a COALESCE/NULLIF combo if you prefer, but CASE is more straightforward here.
Quick Summary
While there’s no single "drop-in" function like NVL for this exact scenario, regex-based checks paired with simple conditional logic (CASE or database-specific shorthands) are far cleaner than writing complex nested CASE statements. The key is defining your valid number rules clearly, then using regex to enforce them.
内容的提问来源于stack exchange,提问作者Giulio Angioli

