select into 临时表再使用过程中所遇到的问题和相应的解决方案

来源:互联网 发布:淘宝Dreamweaver 编辑:程序博客网 时间:2024/04/29 17:05

使用中发现 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)属性,否则某些系统中使用中文时会出现乱码. 

原创粉丝点击