IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_report_data]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_report_data]
GO
-- =============================================
-- Author:  flobit
-- Create date: 2018年1月31日
-- Description: 执行报表模板所获取数据的SQL
-- =============================================
CREATE PROCEDURE [dbo].[mps_g_report_data]
@cmpid int,
@branchid int,
@useruid int,
@userdpid int,
@userotid int,
@rpt_id int,
@rpt_data varchar(max)
AS
BEGIN
SET NOCOUNT ON;
declare @sql nvarchar(max)
--获取需需要执行的SQL
select @sql=rpt_sql 
from mps_report 
where rpt_id=@rpt_id
--替换参数到SQL中
--替换基本参数
set @sql=REPLACE(@sql,'{cmpid}',@cmpid)
set @sql=REPLACE(@sql,'{branchid}',@branchid)
set @sql=REPLACE(@sql,'{useruid}',@useruid)
set @sql=REPLACE(@sql,'{userdpid}',@userdpid)
set @sql=REPLACE(@sql,'{userotid}',@userotid)

--替换隐含参数
declare @tmp varchar(max)=@rpt_data
declare @item varchar(max)=@rpt_data
declare @index int =  0
declare @splitor varchar(32) = '___SPLITOR___'
while @tmp > ''
begin
set @index = CHARINDEX(@splitor,@tmp)
--只有一个参数的时候
set @item = CASE WHEN @INDEX>0 THEN SUBSTRING(@tmp,1,@index-1) ELSE @tmp END
set @tmp = CASE WHEN @INDEX>0 THEN SUBSTRING(@tmp,@index+LEN(@splitor),LEN(@tmp)) ELSE '' END
if @item>''
begin
--拆分键值对
set @index = CHARINDEX('=',@item);
if @index > 0
begin
set @sql=REPLACE(@sql,'{'+SUBSTRING(@item,1,@index-1)+'}',SUBSTRING(@item,@index+1,LEN(@item)))
end
end
end
if @sql is not null and LEN(@sql) >0
BEGIN
exec sp_executesql @sql
END
END