【MSSQL】 SELECT INTO 字段长度问题

场景:

需要用select into 创建表,然后后续还有新的数据需要使用Insert into插入。结果多次测试,在insert into 的时候提示

消息 8152,级别 16,状态 14,第 7 行
将截断字符串或二进制数据。

最终发现select into 的时候字段数据短一点,然后到了insert into的时候,数据长了所以就超了,原理暂时没有特别清晰,但是是这个问题。文章尾部更新验证这个情况

 

下面开始还原场景:

 select '12' as fmnam into temp
 insert temp 
 select '986-57(胶箱出货)'
 DROP TABLE TEMP

第二次测试,使用N 

 select N'12' as fmnam into temp
 insert temp 
 select N'986-57(胶箱出货)'
 DROP TABLE TEMP

 

最后一次测试,想到是不是因为初始的长度可能就是固定了,那么在select into 的时候我给他cast一次,设置长度为nvarchar(max)

 select CAST('12' as varchar(max)) as fmnam into temp 
 insert temp 
 select '986-57(胶箱出货)'
 DROP TABLE TEMP

测试结果OK。那么可以猜测,是select into的时候为了性能,是直接吧第一行的长度作为了字段的长度,导致我后续insert into 的时候截断了。

第一次遇到这种情况,特意记录。

验证

先select into 创建表

 select N'12' as fmnam into temptemptemptemptemp

然后打开SSMS  找到表,右键设计

结果真的是你插入数据的长度就是这个字段的长度。

select CAST('12' as varchar(max)) as fmnam into temptemptemptemptemp 

原文地址:https://www.cnblogs.com/jlz-s/p/10026020.html