编写了如下脚本,统计各种职务的收入情况:
SELECT
UU.JName as '职务',
SUM(UU.Salary) as '薪酬总额',
count(UU.Pid) as '平均人数',
SUM(UU.Salary)/count(UU.Pid) as '人均收入'
FROM
(SELECT
TT.Psid as Pid,
JOB.FName_L2 as JName,
TT.Sal as Salary
FROM
(SELECT
SCH.FPersonID as Psid,
PON.FJobID as JobID,
SCH.FFSAL251 as Sal
FROM T_HR_SCHM_31247124924456 AS SCH
LEFT OUTER JOIN T_BD_Person AS PS ON SCH.FPersonID = PS.FID
LEFT OUTER JOIN T_HR_PersonPosition AS PPS ON PS.FID = PPS.FPersonID
LEFT OUTER JOIN T_ORG_Position AS PON ON PPS.FPrimaryPositionID = PON.FID
)AS TT
RIGHT OUTER JOIN T_ORG_JOB AS JOB ON TT.JobID = JOB.FID) AS UU
GROUP BY UU.JName
上面脚本中表名T_HR_SCHM_31247124924456,实际中必须是动态的表名,表名由以下语句得到
select FHorTableName from T_HR_CMPSCHEME where FName_L2 like '在职员工薪酬方案%' (其中where后面不固定,不同的方案对应的表名不同)
请问怎么写出满足要求的语句?
最容易想到的可能就是动态拼接字符串了!!
declare @strsql varchar(max),@strwhere varchar(200)
set @strwhere = '在职员工薪酬方案%'
set @strsql = '
SELECT
UU.JName as ''职务'',
SUM(UU.Salary) as ''薪酬总额'',
count(UU.Pid) as ''平均人数'',
SUM(UU.Salary)/count(UU.Pid) as ''人均收入''
FROM
(SELECT
TT.Psid as Pid,
JOB.FName_L2 as JName,
TT.Sal as Salary
FROM
(SELECT
SCH.FPersonID as Psid,
PON.FJobID as JobID,
SCH.FFSAL251 as Sal
FROM (select FHorTableName from T_HR_CMPSCHEME where FName_L2 like ''' + @strwhere + ''') AS SCH
LEFT OUTER JOIN T_BD_Person AS PS ON SCH.FPersonID = PS.FID
LEFT OUTER JOIN T_HR_PersonPosition AS PPS ON PS.FID = PPS.FPersonID
LEFT OUTER JOIN T_ORG_Position AS PON ON PPS.FPrimaryPositionID = PON.FID
)AS TT
RIGHT OUTER JOIN T_ORG_JOB AS JOB ON TT.JobID = JOB.FID) AS UU
GROUP BY UU.JName'
我觉得有两思路:
第一种:首先考虑的是,给配置方案设置一个配置表,其中包含的表名。以后维护方案时同步维护该配置信息。
第二种:动态拼接SQL,这是有注入风险。一些通用的分页存储过程都采用动态表名,你可以参考。
针对你的问题我觉得你完全可以使用一张临时表来解决,你看你问题中提到的表明 T_HR_SCHM_31247124924456 是动态生成的,其实你可以理解为他是临时生成的,也就是说由你"select FHorTableName from T_HR_CMPSCHEME where FName_L2 like '在职员工薪酬方案%' (其中where后面不固定,不同的方案对应的表名不同)"这个部分来生成的,like里面的条件是传入的吧??那你这里为什么不select * into #T_HR_SCHM_Temp from T_HR_CMPSCHEME where FName_L2 like '在职员工薪酬方案%'这样子来做呢?然后前面的语句就直接是
SELECT
UU.JName as '职务',
SUM(UU.Salary) as '薪酬总额',
count(UU.Pid) as '平均人数',
SUM(UU.Salary)/count(UU.Pid) as '人均收入'
FROM
(SELECT
TT.Psid as Pid,
JOB.FName_L2 as JName,
TT.Sal as Salary
FROM
(SELECT
SCH.FPersonID as Psid,
PON.FJobID as JobID,
SCH.FFSAL251 as Sal
FROM #T_HR_SCHM_Temp AS SCH
LEFT OUTER JOIN T_BD_Person AS PS ON SCH.FPersonID = PS.FID
LEFT OUTER JOIN T_HR_PersonPosition AS PPS ON PS.FID = PPS.FPersonID
LEFT OUTER JOIN T_ORG_Position AS PON ON PPS.FPrimaryPositionID = PON.FID
)AS TT
RIGHT OUTER JOIN T_ORG_JOB AS JOB ON TT.JobID = JOB.FID) AS UU
GROUP BY UU.JName
最后再删除掉#T_HR_SCHM_Temp这张表就好。