日期:2014-05-18  浏览次数:20854 次

求一个动态SQL语句,运行后报错误(在应使用条件的上下文(在 'StationName' 附近)中指定了非布尔类型的表达式。)急!!

ALTER Proc [dbo].[proc_get_HalfHistory2]
  @StationName varchar(50),
  @stime varchar(200),--时间从
  @etime varchar(200)--至
as
declare @cs varchar(50),@sql varchar(1000)

begin
set @cs=(select case gongzuoxuanxiang when '1'then '加压泵1电流' when '2'then '加压泵2电流' when '3' then '加压泵3电流' when '4' then '加压泵4电流' when '5' then '加压泵5电流' when '6' then '加压泵6电流' when '7' then '深井泵1电流' when '8' then '深井泵2电流' when '9' then '深井泵3电流' when '10' then '深井1水位' when '11' then '水池水位' when '13' then '压力返馈' end from MoNiLiangShuRuShangZai where dtuid=@StationName and lushu=1)
set @sql='
select distinct c.StationName as 站名,Testtime as 召测时间 ,PPower as 总功率 ,Allrunning as 总瞬时流量,Running1 as 瞬时流量1,Running2 as 瞬时流量2,Running3 as 瞬时流量3,
Running4 as 瞬时流量4,Running5 as 瞬时流量5,Running6 as 瞬时流量6,Running7 as 瞬时流量7,Running8 as 瞬时流量8,Alltotalrunning as 总累计流量,
Totalrunning1 as 累计流量1,Totalrunning2 as 累计流量2,Totalrunning3 as 累计流量3,Totalrunning4 as 累计流量4,Totalrunning5 as 累计流量5,
Totalrunning6 as 累计流量6,Totalrunning7 as 累计流量7,Totalrunning8 as 累计流量8, UsePower as 耗电量,
Atension as A电压,Btension as B相电压,Ctension as C相电压,Aelectric as A相电流,Belectric as B相电流,Celectric as C相电流,Demo1 as '+@cs+'
from History a LEFT OUTER JOIN Stationinfo c ON a.StationName=c.Agreement where a.StationName='+@StationName +' and Time between '+@stime+' and '+@etime+''
exec(@sql)
end

在应使用条件的上下文(在 'StationName' 附近)中指定了非布尔类型的表达式。
where条件那里有错误,如何修改呀

------解决方案--------------------
在exec前加Print(@Sql);
比较大的可能是 Where a.StationName='+@StationName中@StationName的类型有问题
------解决方案--------------------
SQL code

where a.StationName='''+@StationName +''' and Time between '''+@stime+''' and '''+@etime+''''

------解决方案--------------------
把declare @cs varchar(50),@sql varchar(1000)
改成declare @cs varchar(2000),@sql varchar(8000)
另外先print(@sql),看下拼成的sql代码是否有错误提示。
------解决方案--------------------
动态字符串的规则:StationName='''+@StationName +''' and Time between '''+@stime+''' and '''+@etime+''''