读书人

简单动态,出错,求改正?该如何处理

发布时间: 2012-02-26 20:19:45 作者: rapoo

简单动态,出错,求改正???
declare @table nvarchar(4000),
@id int,
@sql nvarchar(4000)
select @table= 'bbb ',@id=50
set @sql= 'select top 100 * from '+@table+ ' where id < '+@id

exec(@sql)
============
消息 245,级别 16,状态 1,第 6 行
在将 nvarchar 值 'select top 100 * from bbb where id < ' 转换成数据类型 int 时失败。

[解决办法]
declare @table nvarchar(4000),
@id int,
@sql nvarchar(4000)
select @table= 'bbb ',@id=50
set @sql= 'select top 100 * from '+@table+ ' where id < '+Cast(@id As Varchar)

exec(@sql)
[解决办法]
declare @table nvarchar(4000),
@id int,
@sql nvarchar(4000)
select @table= 'bbb ',@id=50
set @sql= 'select top 100 * from ' '+@table+ ' ' where id < '+@id

exec(@sql)

[解决办法]
@id是int型,相加时把前面字符串强制转换成int型,当然出错。

declare @table nvarchar(4000),
@id nvarchar(10),
@sql nvarchar(4000)
select @table= 'bbb ',@id= '50 '
set @sql= 'select top 100 * from '+@table+ ' where id < '+@id

读书人网 >SQL Server

热点推荐