动态行列转换问题
declare @sql2 varchar(8000)
set @sql2 = 'select cp.corpname, dt.deptname,
pbc.pname, pc.duty,pc.pcl, pbc.pk_psnbasdoc '
select @sql2=@sql2+',sum(case cz.corsename when '''+corsename+''' and charindex('','', '','' , '',''+ge.pk_psncores+'','') > 0 then 1 else 0 end) [' + corsename + ']'
from (select corsename from psncorse ) as a
set @sql2 = @sql2 +' from psnbasdoc pbc
join psndoc pc on pbc.pk_psnbasdoc=pc.pk_psnbasdoc
join dept dt on pc.pk_dept=dt.pk_dept
join corp cp on dt.pk_corp=cp.pk_corp
join psnscore ge on pc.pk_psndoc=ge.pk_psndoc
join psncorse cz on cz.pk_psncorse=ge.pk_psncorse
group by cp.corpname, dt.deptname,
pbc.pname, pc.duty,pc.pcl ,pbc.pk_psnbasdoc'
exec(@sql2)
查询时消息 156,级别 15,状态 1,第 2 行
关键字 'and' 附近有语法错误。
帮我看看那出错了!
------解决方案--------------------
declare @sql2 varchar(8000)
set @sql2 = 'select cp.corpname, dt.deptname,
pbc.pname, pc.duty,pc.pcl, pbc.pk_psnbasdoc '
select @sql2=@sql2+',sum(case cz.corsename when '''+corsename+''' and charindex('','', '','' , '',''+ge.pk_psncores+'','') > 0 then 1 else 0 end) [' + corsename + ']'
from (select corsename from psncorse ) as a
set @sql2 = @sql2 +' from psnbasdoc pbc
join psndoc pc on pbc.pk_psnbasdoc=pc.pk_psnbasdoc
join dept dt on pc.pk_dept=dt.pk_dept
join corp cp on dt.pk_corp=cp.pk_corp
join psnscore ge on pc.pk_psndoc=ge.pk_psndoc
join psncorse cz on cz.pk_psncorse=ge.pk_psncorse
group by cp.corpname, dt.deptname,
pbc.pname, pc.duty,pc.pcl ,pbc.pk_psnbasdoc'
红字那里,那个有问题,比如case when a and charindex('','', '','' , '',''+ge.pk_psncores+'','') > 0 你觉得这样对吗?最起码要case when a>0 and charindex('','', '','' , '',''+ge.pk_psncores+'','') > 0 之类的才行