当前位置: 代码迷 >> Sql Server >> 简单动态,出错,求改正?该如何处理
  详细解决方案

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

热度:53   发布时间:2016-04-27 16:05:15.0
简单动态,出错,求改正???
declare   @table   nvarchar(4000),
                @id   int,
                @sql   nvarchar(4000)
select   @table= 'bbb ',@id=50
set   @sql= 'select   top   100   *   from   '[email protected]+ '   where   id <   '[email protected]

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 '[email protected]+ ' 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 ' '[email protected]+ ' ' where id < '[email protected]

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 '[email protected]+ ' where id < '[email protected]
  相关解决方案