奇怪的行为:T-sql char/string 连接字符

Strange behavior: T-sql char/string concatenation char

我在 t-sql 中有一个奇怪的行为。进行以下测试

   DECLARE @a char(22) = 'John went to buy a car', @b char(15)= 'Tom went to pub';  
   SELECT IIF(1=1 , @a, @b )+'. He met a friend';

输出正常: 约翰去买车了。他认识了一个朋友。

   SELECT IIF(1=2 , @a, @b )+'. He met a friend';

输出错误:

    Tom went to pub       . He met a friend.

如果 test 为真,则变量 char 的串联分配 22 个字符,否则分配 22 个字符!因此,在通过 IIF 进行的字符连接中(但同样发生在 CASE 中)输出被分配给第一个表达式(@b 变量被认为是 22 个字符!)有什么想法吗?

一个IIF是一个表达式,因此需要一个数据类型。这种数据类型 不能 取决于执行时发生的情况 - 它需要在查询编译时知道。

因此,假设两个输入是 char(22)char(15),T-SQL 为整个 表达式选择的数据类型 是这两个中的 'wider',更具包容性——即 char(22)

因此无论执行时结果如何,结果的 类型 都将是 char(22)。正如您所观察到的,这意味着有时结果与所选输入相比 space-padded。


有趣的是,我实际上无法在 the documentation for IIF 的任何地方找到明确调用的此行为。上面写着

Returns the data type with the highest precedence from the types in true_value and false_value. For more information, see Data Type Precedence (Transact-SQL)

但是 linked page on Precedence 实际上并没有指出固定长度的字符类型会发生什么,例如charvarchar,除非我错过了。