SQL variable
数据类型和 Table column
数据类型有什么区别。
考虑下面的例子:
DECLARE @variable CHAR(1)
SET @variable = 'quarter'
SELECT @variable --works
结果:Q
但是当我在表中执行相同操作时出现错误
DECLARE @table TABLE
(
col CHAR(1)
)
INSERT INTO @table
VALUES ('quarter') --Fails
Msg 8152, Level 16, State 14, Line 9 String or binary data would be truncated.
我浏览了 MSDN 关于 DECLARE @local_variable仍然没有得到任何答复。谁能告诉我这是什么原因。
最佳答案
主要区别在于SET
与INSERT
中的警告如何工作,这里是SET ANSI_WARNINGS documentation
When set to ON, the divide-by-zero and arithmetic overflow errors cause the statement to be rolled back and an error message is generated. When set to OFF, the divide-by-zero and arithmetic overflow errors cause null values to be returned. The behavior in which a divide-by-zero or arithmetic overflow error causes null values to be returned occurs
if an INSERT or UPDATE is tried on a character, Unicode, or binary column in which the length of a new value exceeds the maximum size of the column. If SET ANSI_WARNINGS is ON, the INSERT or UPDATE is canceled as specified by the ISO standard.
Trailing blanks are ignored for character columns and trailing nulls are ignored for binary columns. When OFF, data is truncated to the size of the column and the statement succeeds.
但是,它不会影响 SET 语句:
ANSI_WARNINGS is not honored when passing parameters in a stored procedure, user-defined function, or when declaring and
setting variables
in a batch statement. For example,if a variable is defined as char(3), and then set to a value larger than three characters, the data is truncated to the defined size
and the INSERT or UPDATE statement succeeds.
因此,您可以禁用 ansi 警告,并且您的插入查询将起作用。但我更喜欢打开警告,但在应用程序端进行数据验证/截断。
关于sql - SQL变量数据类型和表列数据类型之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35090511/