IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_sys_calc_bizauthority]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_sys_calc_bizauthority]
GO
create procedure [dbo].[mps_sys_calc_bizauthority](
@cmpid int ,
@bizid int
)
as
begin
 
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 
declare @tbname varchar(50)
declare @dbname varchar(50)
declare @fkey   varchar(50) 
exec sys_sql_getTableNamePk @cmpid,'biz',@bizid,0,@tbname output,@fkey output ,@dbname output 

declare @str nvarchar(2000) 
select @str  =  biz_authority_factor from mps_biztype with(nolock) where biz_id = @bizid
set @str = ISNULL(@str,'') 
if (@str='') set @str='ord_createcuid' 
declare @exp nvarchar(4000) 
select @exp=dbo.mps_sys_gen_powerfactor(@cmpid,'biz',@bizid,@str) 

print '计算权限因子,'+@dbname+@tbname+'_authority_factor..'
declare @s nvarchar(max) = '' 
set @s='
truncate table '+@dbname+@tbname+'_authority_factor 
insert into '+@dbname+@tbname+'_authority_factor(ordaf_done,ordaf_ordid,ordaf_value)
select 1,MIN(ord_id), substring(sys.fn_sqlvarbasetostr(HashBytes(''MD5'',convert(varchar(100),'+@exp+'))),3,32) aa from '+@dbname+@tbname+' with(nolock) 
group by substring(sys.fn_sqlvarbasetostr(HashBytes(''MD5'',convert(varchar(100),'+@exp+'))),3,32) 
'
execute(@s) 

print '将权限因子写回'+@dbname+@tbname
if (@str='ord_createcuid') 
begin
set @s='
truncate table md5cuid 
insert into md5cuid(md5,cuid,value) 
select ordaf_value,ord_createcuid,ordaf_id from '+@dbname+@tbname+'_authority_factor with(nolock) , '+@dbname+@tbname+' with(nolock) 
where ordaf_ordid=ord_id 
update '+@dbname+@tbname+' set ord_authority_factor=value from md5cuid with(nolock) 
where ord_createcuid=cuid ' 
end else 
begin
set @s='
update '+@dbname+@tbname+' set ord_authority_factor=ordaf_id from '+@dbname+@tbname+'_authority_factor with(nolock) 
where substring(sys.fn_sqlvarbasetostr(HashBytes(''MD5'',convert(varchar(100),'+@exp+'))),3,32)=ordaf_value ' 
end
execute(@s) 

print '将创建人写入,'+@dbname+@tbname+'_authority..'
set @s='
truncate table '+@dbname+@tbname+'_authority 
insert into '+@dbname+@tbname+'_authority(orda_auto,orda_cuid,orda_ordafid) 
select -1 , ord_createcuid,ordaf_id 
from '+@dbname+@tbname+'_authority_factor with(nolock) ,'+@dbname+@tbname+' with(nolock) where ordaf_ordid=ord_id 
' 

print '计算权限,'+@dbname+@tbname+'_authority..'

set @s='
declare @ss nvarchar(max) = '''' 
select @ss = @ss+case when @ss='''' then '''' else '','' end + CONVERT(varchar(10),ordaf_ordid)+'':''+CONVERT(varchar(10),ordaf_id) 
from '+@dbname+@tbname+'_authority_factor order  by ordaf_ordid 
exec mps_sys_calc_bizpower_authority '+CONVERT(varchar(10),@cmpid)+','+CONVERT(varchar(10),@bizid)+',@ss  
'
execute(@s) 
end