本帖最后由 successit 于 2021-9-16 08:51 编辑
前提条件:创建两张视图,分别为:v_GZL_DB_A 及 v_GZL_YB_A ,如果不创建,可以在存储过程里添加检测视图是否存在,如果存在,则更新,如果不存在则创建,我这里是已经建好的,所以略过
这个方法就在于,当系统中开启一个新的工作流后,由存储过程自动把新增的工作流待办及已办历史信息表更新到原有的视图语句中去,同时还解决一个就是开启新的工作流后,工作流历史记录表,并不会创建,当有人提交一条工作流后才会创建,如果存储过程设置了触发机制,那当有人提交了工作流后,数据库就会自动去更新对应的视图,免去人为维护
存储过程代码如下:
ALTER PROC [dbo].[p_GZL_DBView_Alt]
AS
BEGIN
--获取数据库中包含FGC_WHT字符的数据表名,并与当前已办视图比对,如果没有新增的工作流视图表返回,如果有,则去更新已办和待办视图
DECLARE @DB_Count AS int
set @DB_Count =
(select count(dbname)
from
(SELECT name as dbname FROM SYS.SYSOBJECTS WHERE type='U' AND [name] LIKE '%_FGC_WHT%'
except
SELECT DISTINCT dbname FROM v_GZL_YB_A) t)
IF @DB_Count = 0
RETURN
ELSE
DECLARE @已办 VARCHAR(MAX)
DECLARE @待办 VARCHAR(MAX)
--DECLARE @FGC_AssignTo VARCHAR(MAX)
--SET @FGC_AssignTo = 'substring(REPLACE(REPLACE(FGC_AssignTo, CHAR(13), '''') , CHAR(10),'',''),2,LEN(REPLACE(REPLACE(FGC_AssignTo, CHAR(13), '''') , CHAR(10),'','')) - 2) AS AssignTo ' ---把默认的待办人去除空格及回车符
SET @已办=''
SET @待办=''
----获取所有工作流历史视图表及所需字段,并用UNION ALL 组合起来,得到历史视图语句
SELECT @已办=@已办 +CHAR(13)+CHAR(10)+'UNION ALL' + CHAR(13)+CHAR(10) + 'SELECT' + ' ''' + ''+[name]+'' + ''' '+ 'AS DBname,ID AS 历史表ID,RecordId AS 原表ID,Who AS 办理人,[When] AS 办理时间,FGC_State AS 办理节点,'+''''+[name]+'''' + '+' + '''_'''+'+'+'CAST(ID AS NVARCHAR(50)) AS 唯一码
FROM ['+[name]+']'
FROM SYS.SYSOBJECTS
WHERE type='U' AND [name] LIKE '%_FGC_WHT%'
----根据历史视图表,去掉后缀_FGC_WHT字符,得到原表,并用UNION ALL组合起来,得到原表待办视图语句
SELECT @待办=@待办 +CHAR(13)+CHAR(10)+'UNION ALL' + CHAR(13)+CHAR(10) + 'SELECT' + ' ''' + ''+REPLACE([name],'_FGC_WHT','')+'' + ''' '+ 'AS DBname,ID AS 原表ID,FGC_State,FGC_AssignTo,'+''''+REPLACE([name],'_FGC_WHT','')+'''' + '+' + '''_'''+'+'+'CAST(ID AS NVARCHAR(50)) AS 唯一码
FROM ['+REPLACE([name],'_FGC_WHT','')+']' + ' ' + 'WHERE ISNULL(FGC_AssignTo,'''') <> '''''
FROM SYS.SYSOBJECTS
WHERE type='U' AND [name] LIKE '%_FGC_WHT%'
-----去除语句的多于拼接字符-----
SET @已办=STUFF(@已办,1,11,'')
SET @待办=STUFF(@待办,1,11,'')
-----把已办视图用胡老板的WITH AS拼接
SET @已办 =
'WITH CTE AS ('
+@已办+CHAR(13)+CHAR(10)+
')
SELECT
(SELECT COUNT(*) FROM CTE B WHERE A.唯一码 >= B.唯一码) AS ID,
DBname AS DBname,
历史表ID ,
原表ID,
办理人,
办理时间,
办理节点
FROM CTE AS A'
--PRINT @已办 ----查看拼接后的SQL语句
--EXEC (@已办) ----测试执行拼接后的SQL语句
-----创建并执行已办视图更新
DECLARE @已办视图 varchar(MAX)
SET @已办视图 = ('ALTER VIEW v_GZL_YB_A AS' + CHAR(13)+CHAR(10) + @已办 )
EXEC (@已办视图)
-----把待办视图用胡老板的WITH AS拼接----
SET @待办 =
'WITH CTE AS ('
+@待办+CHAR(13)+CHAR(10)+
')
SELECT
(SELECT COUNT(*) FROM CTE B WHERE A.唯一码 >= B.唯一码) AS ID,
DBname AS DBname,
FGC_AssignTo AS AssignTo,
FGC_State AS State,
原表ID
FROM CTE AS A'
----创建并执行待办视图更新----
DECLARE @待办视图 varchar(MAX)
SET @待办视图 = ('ALTER VIEW v_GZL_DB_A AS' + CHAR(13)+CHAR(10) + @待办 )
EXEC (@待办视图)
END
GO
|