在 SQL 服务器 table 中插入数据在两种情况下均未显示错误

Inserting data in SQL Server table not showing error on both condition

我使用程序将数据插入 table 以获得固定的列大小。但是数据trim并且插入成功没有任何错误。

我丢失了该变量的一些内容。

此代码段显示任何错误:

declare @temp varchar(5)
declare @tm table (a varchar(5))
set @temp ='abcdefghijkl'

insert into @tm 
values(@temp)

select * from @tm

但此代码片段 显示此错误:

String or binary data would be truncated

declare @temp1 varchar(5)
declare @tm1 table (a varchar(5))

insert into @tm1 
values('abcdefghijkl')

select * from @tm1

第二个代码片段引发错误是件好事。
它可以防止您错误地破坏数据。

但是,在第一个代码片段中,SQL 服务器会根据隐式转换规则静默 trim 字符串。
每当您尝试使用具有不同数据类型的数据填充变量时,SQL 服务器将尝试将数据类型隐式转换为变量的数据类型。

这在 char 和 varchar (Transact-SQL) 页面的 Converting Character Data 部分有详细记录:

When character expressions are converted to a character data type of a different size, values that are too long for the new data type are truncated.

插入 table 时不会发生这种情况,前提是 ANSI_WARNINGS 设置为 ON(默认状态)。
ANSI_WARNINGS 设置为 ON 时,您会得到

String or binary data would be truncated

错误信息。
但是,当它设置为 OFF 时,隐式转换将静默截断数据:

set ansi_warnings off;

declare @temp1 varchar(5)
declare @tm1 table (a varchar(5))

insert into @tm1 
values('abcdefghijkl')

select * from @tm1

结果:

a
abcde

注意: ansi_warnings 状态在设置变量值时不影响隐式转换 - 无论 ansi_warnings状态。