select into 臨時表再使用過程中所遇到的問題和相應的解決方案

使用中發現 select into 臨時表 很麻煩,下面是使用中發現的一些注意事項(一下以mssqlserver爲例):

1,一般使用

create table person (id int ,name varchar(20),birthday datetime)

讀取數據到臨時表中 select * into #tb_tmp from person where ....
使用臨時表中的數據 select name from #tb_tmp where id = 1
使用之後不要忘記刪除臨時表(drop table #tb_tmp),否則下次使用時會報錯如:
消息 2714,級別 16,狀態 6,第 1 行
There is already an object named '#tb_tmp' in the database.

2,常見問題
select  '' as col into #tb_tmp
會包如下錯誤:
消息 2731,級別 16,狀態 1,第 2 行
Column 'col' has invalid width: 0.

解決以上問題有兩種方法:
解決方案一,''->null
 select null as col into #tb_tmp
解決方案二,''->ltrim(' ') or ''->rtrim(' ')
 select rtrim(' ') as col into #tb_tmp 

解決方案一引發的問題:
插入問題:只能插入int數字或數字類字符串(其中插入帶小數的數字,小數部分會被自動去除)
如果插入數字以外的字符串,如:insert into #tb_tmp values('asdfsadf')會報如下錯誤:
消息 245,級別 16,狀態 1,第 3 行
Syntax error converting the varchar value 'asdfsadf' to a column of data type int.

解決方案二引發的問題:
插入問題:只能插入 "('空格數')"中指定空格數範圍內數量的字符串,當字符串中個數大於括號中指定空格數時報如下錯誤:
消息 8152,級別 16,狀態 9,第 2 行
String or binary data would be truncated.
The statement has been terminated.

總結:select into 所引發的問題不能很好解決,建議使用臨時表前先定義臨時表的完整結構,並再定義列時加上(COLLATE

DATABASE_DEFAULT)屬性,否則某些系統中使用中文時會出現亂碼. 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章