場景:
需要用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