SQL Server 2005 插入 table select 查询的预期行为是什么,其中一列尝试转换空值

What is SQL Server 2005 expected behavior of insert into table select query where one of the columns attempts to convert a null value

我们在一些遗留 SQL Server 2005 代码中有一个声明,例如

insert into myTable
select distinct 
   wherefield1, 
   wherefield2,
   anotherfield,
   convert(numeric(10,2), varcharfield1),
   convert(numeric(10,2), varcharfield2),
   convert(numeric(10,2), varcharfield3),
   convert(datetime, varcharfield4),
   otherfields
from myStagingTable
where insertflag='true'
and wherefield1 = @wherevalue1
and wherefield2 = @wherevalue2

在代码的前面,设置了一个变量来确定 varcharfield1 或 varcharfield2 是否为空,并且只要其中一个不为空,插入程序就会执行。

我们知道,如果varcharfield1、varcharfield2、varcharfield3是非数字字符串,就会抛出异常,不会插入。但是当这些变量之一为 null 时,我对这种行为感到困惑,因为它经常是这样。实际上,这些值之一总是空的。但似乎插入确实发生了。看起来遗留代码依赖于此来防止仅插入非数字字符数据,同时允许插入空值或空值(在前面的步骤中,myStagingTable 的这些字段中的所有空字符串都被替换为空值)。

这已经 运行 在 Production SQL Server 2005 实例上使用所有默认设置多年了。如果我们升级到更新版本的 SQL 服务器,我们可以依赖这种行为吗?

谢谢,

丽贝卡

NULL 转换为任何内容仍然是 NULL。如果该列允许 NULL,这就是您将得到的。如果该列不可为空,它将失败。

您甚至无需执行 INSERT 操作就可以自己看到。只是 运行 这个:

SELECT CONVERT(numeric(10,2), NULL)

并注意它是如何产生 NULL 结果的。然后 运行 这个:

SELECT CONVERT(numeric(10,2), 'x')

并注意它是如何抛出错误消息而不是返回任何内容的。