sql:Cast:Convert

declare @chengji int,@sql varchar(800)
select @chengji=70
set @sql='select * from stu where 成绩='+@chengji
print @sql
以上为什么不行?在将 varchar 值 'select * from stu where 成绩=' 转换成数据类型 int 时失败
declare @chengji varchar(800),@sql varchar(800)
select @chengji='a'
set @sql='select * from stu where 成绩='''+@chengji+''''
print @sql
以上为什么行?

答:
因为@chengji是整型,整型不能和字符型直接用+号连接,要先转为字符型再连接
试试:
declare   @chengji   int,@sql   varchar(800
select   @chengji=70 
set   @sql= 'select   *   from   stu   where   成绩= '+rtrim(@chengji
print   @sql 
正常
declare   @chengji   int,@sql   varchar(800
select   @chengji=70 
set   @sql= 'select   *   from   stu   where   成绩= '+cast(@chengji   as   varchar(10)) 
print   @sql 
正常
declare   @chengji   int,@sql   varchar(800
select   @chengji=70 
set   @sql= 'select   *   from   stu   where   成绩= '+convert(varchar(10),@chengji
print   @sql 
正常
其实本问题没有什么具体意思,因为select * from stu where 成绩 根本不是用来执行的,只是作为字符出现,完全可以用aaa bbb来代替,不懂提问者为什么这么问?

posted on 2007-11-22 16:15  simhare  阅读(1477)  评论(0)    收藏  举报

导航