IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_save_authority_factor]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_save_authority_factor]
GO
create proc [dbo].[mps_save_authority_factor]
@cmpid int,
@bizid int,
@condition nvarchar(4000)
as
begin
set nocount on

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
declare @bizfactor nvarchar(4000)
declare @factorfunc nvarchar(4000)
declare @sqlstr nvarchar(max)

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 

--查询biz_authority_factor值，用于比较是否改变
select @bizfactor = biz_authority_factor from mps_biztype 
where biz_cmpid = @cmpid and biz_id = @bizid 

if @condition != @bizfactor
begin
select @factorfunc =  dbo.mps_sys_gen_powerfactor(@cmpid,'biz',@bizid,@condition)
select @factorfunc as cc
--重新计算权限因子
set @sqlstr = ' 
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'','+@factorfunc+')),3,32) aa from '+@dbname+@tbname+' with(nolock) 
group by substring(sys.fn_sqlvarbasetostr(HashBytes(''MD5'','+@factorfunc+')),3,32 )'
--更新order表中的ord_authority_factor值
set @sqlstr = @sqlstr + ' 
    update '+@dbname+@tbname+' set ord_authority_factor = b.ordaf_id
from '+@dbname+@tbname+'_authority_factor b
where substring(sys.fn_sqlvarbasetostr(HashBytes(''MD5'','+@factorfunc+')),3,32)=b.ordaf_value

    '
exec(@sqlstr)
select @sqlstr as insertsql
--更新值
update mps_biztype set biz_authority_factor = @condition
where biz_cmpid = @cmpid and biz_id = @bizid
--插入权限计算命令
insert into mps_command(cmd_code,cmd_time,cmd_cmpid)
values('rightAll',GETDATE(),@cmpid)
end

set nocount off
end