SQL 服务器中 ISNULL 函数的截断问题
Truncation issue with ISNULL function in SQL Server
最近我遇到这样一种情况,如果第一个字符串为 null,ISNULL
函数会 return 向我发送截断数据。
ISNULL(a, b);
我发现 a 是 5 个字符,b 是 10 个字符,但是当 a 为 null 时,它将 return 只有 5 个字符的 b 而不是全长。
这是一个已知问题吗?
这是已知行为
来自MSDN
The value of check_expression is returned if it is not NULL;
otherwise, replacement_value is returned after it is implicitly
converted to the type of check_expression, if the types are different.
replacement_value can be truncated if replacement_value is longer than
check_expression.
使用COALESCE
解决这个问题
SELECT COALESCE(a, b) From yourtable
这是一个演示
CREATE TABLE #nulltest
(
a CHAR(5),
b CHAR(10)
)
INSERT INTO #nulltest
VALUES ('12345','1234567890'),
(NULL,'1234567890')
SELECT a,
b,
ISNULL(a, b) AS Isnull_Result,
COALESCE(a, b) AS Coalesce_Result
FROM #nulltest
结果:
╔═══════╦════════════╦═══════════════╦═════════════════╗
║ a ║ b ║ Isnull_Result ║ Coalesce_Result ║
╠═══════╬════════════╬═══════════════╬═════════════════╣
║ 12345 ║ 1234567890 ║ 12345 ║ 12345 ║
║ NULL ║ 1234567890 ║ 12345 ║ 1234567890 ║
╚═══════╩════════════╩═══════════════╩═════════════════╝
除了@Prdp 答案之外,您还可以使用 CASE WHEN。
CASE WHEN a is null then b else a end AS caseWhen_Result
最近我遇到这样一种情况,如果第一个字符串为 null,ISNULL
函数会 return 向我发送截断数据。
ISNULL(a, b);
我发现 a 是 5 个字符,b 是 10 个字符,但是当 a 为 null 时,它将 return 只有 5 个字符的 b 而不是全长。
这是一个已知问题吗?
这是已知行为
来自MSDN
The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different. replacement_value can be truncated if replacement_value is longer than check_expression.
使用COALESCE
解决这个问题
SELECT COALESCE(a, b) From yourtable
这是一个演示
CREATE TABLE #nulltest
(
a CHAR(5),
b CHAR(10)
)
INSERT INTO #nulltest
VALUES ('12345','1234567890'),
(NULL,'1234567890')
SELECT a,
b,
ISNULL(a, b) AS Isnull_Result,
COALESCE(a, b) AS Coalesce_Result
FROM #nulltest
结果:
╔═══════╦════════════╦═══════════════╦═════════════════╗
║ a ║ b ║ Isnull_Result ║ Coalesce_Result ║
╠═══════╬════════════╬═══════════════╬═════════════════╣
║ 12345 ║ 1234567890 ║ 12345 ║ 12345 ║
║ NULL ║ 1234567890 ║ 12345 ║ 1234567890 ║
╚═══════╩════════════╩═══════════════╩═════════════════╝
除了@Prdp 答案之外,您还可以使用 CASE WHEN。
CASE WHEN a is null then b else a end AS caseWhen_Result