sql - SQL变量数据类型和表列数据类型之间的区别

标签 sql sql-server variables types

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仍然没有得到任何答复。谁能告诉我这是什么原因。

最佳答案

主要区别在于SETINSERT中的警告如何工作,这里是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/

相关文章:

javascript - 在cherrypy中在python和javascript之间共享变量信息

C++类的指针变量

sql - Oracle 数据库表中的数据加载

mysql - SQL SUM 只返回第一条记录

sql - 获取表列表的行数

asp.net - .NET SQL 连接池如何在多节点环境中扩展?

sql-server - 如何比较 SQL Server 中的日期时间类型

sql - 如何在没有重复的情况下进行多个并发批量插入?

sql - 如何重命名 SQL Server 中名称中带有方括号的内容?

c - 为什么 unsigned int 小于零是可能的?