【问题标题】:String or binary data would be truncated. The statement has been terminated. Simple Error字符串或二进制数据将被截断。该语句已终止。简单错误
【发布时间】:2016-06-23 10:28:22
【问题描述】:
   Create Table rs
   (
   Id int  IDENTITY (1,1) Primary Key,
   mId int Not NUll,
   ad varchar Not NUll,
   stvarchar Not NUll,
   et varchar Not NUll,
   nt varchar(max)
   );


   insert into rs ( nt, et, st, ad, mId) 
values ('as','as','as','as',12)

我收到了这个错误

Msg 8152, Level 16, State 14, Line 2
String or binary data would be truncated.
The statement has been terminated.

这是一个简单的sql,但很难解决它

【问题讨论】:

标签: sql sql-server


【解决方案1】:

您没有为 varchar 变量设置大小,因此大小将默认为 1,因此在将大小为 2 的 varchar 插入表中时出现此错误,请为您的 varchar 变量提供大小以解决这个问题

  Create Table rs
   (
   Id int  IDENTITY (1,1) Primary Key,
   mId int Not NUll,
   ad varchar(10) Not NUll,
   st varchar(10) Not NUll,
   et varchar(10) Not NUll,
   nt varchar(max)
   );

【讨论】:

    【解决方案2】:

    正如@Krish 指出的那样,您需要分配空间。即为每列定义大小

         Create Table rs
       (
         Id int  IDENTITY (1,1) Primary Key,
         mId int Not NUll,
         ad varchar(2) Not NUll,
         st varchar(2) Not NUll,
         et varchar(2) Not NUll,
         nt varchar(max)
       );
    
    
       insert into rs ( nt, et, st, ad, mId) 
       values ('as','as','as','as',12)
    

    默认大小是 1,所以这也应该可以工作......但这不是你想要的(它只是为了解释问题)

    INSERT INTO #rs ( mId, ad, st, et, nt) 
    VALUES (12, 'a','a', 'a', 'a')
    

    【讨论】:

      【解决方案3】:

      来自MSDN

      varchar [ ( n | max ) ]
      可变长度、非 Unicode 字符串数据。 n 定义字符串长度,可以是 1 到 8,000 之间的值。 max 表示最大存储大小为 2^31-1 字节(2 GB)。

      备注 在数据定义或变量声明语句中未指定 n 时,默认长度为 1。使用 CAST 和 CONVERT 函数时未指定 n 时,默认长度为 30。

      指定Varchar 的默认长度。也看看这个article..

         Create Table rs
         (
         Id int  IDENTITY (1,1) Primary Key,
         mId int Not NUll,
         ad varchar(5) Not NUll,
         st varchar(5) Not NUll,
         et varchar(5) Not NUll,
         nt varchar(max)
         );
      
         insert into rs ( nt, et, st, ad, mId) 
         values ('as','as','as','as',12
      

      【讨论】:

        猜你喜欢
        • 2013-03-19
        • 1970-01-01
        • 2012-01-31
        • 2018-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多