-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsqlsetup.sql
326 lines (325 loc) · 539 KB
/
sqlsetup.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
if DATABASE_PRINCIPAL_ID('bpa_ExecuteSP_System') is not null DROP ROLE bpa_ExecuteSP_System; if DATABASE_PRINCIPAL_ID('bpa_ExecuteSP_DataSource_bpSystem') is not null DROP ROLE bpa_ExecuteSP_DataSource_bpSystem; if DATABASE_PRINCIPAL_ID('bpa_ExecuteSP_DataSource_custom') is not null DROP ROLE bpa_ExecuteSP_DataSource_custom; IF object_id('FK_BPAProcess_DefaultRealTimeStatsView') IS NOT NULL ALTER TABLE BPAProcess DROP CONSTRAINT FK_BPAProcess_DefaultRealTimeStatsView IF object_id('FK_BPAProcess') IS NOT NULL ALTER TABLE [BPARealTimeStatsView] DROP CONSTRAINT FK_BPAProcess IF object_id('fk_bpaoldpassword_bpauser') IS NOT NULL ALTER TABLE BPAOldPassword DROP CONSTRAINT fk_bpaoldpassword_bpauser IF object_id('FK_BPAPassword_BPAUser') IS NOT NULL ALTER TABLE BPAPassword DROP CONSTRAINT FK_BPAPassword_BPAUser IF object_id('FK_BPMIConfiguredSnapshot_BPAWorkQueue') IS NOT NULL ALTER TABLE BPMIConfiguredSnapshot DROP CONSTRAINT FK_BPMIConfiguredSnapshot_BPAWorkQueue IF object_id('FK_BPMIQueueSnapshot_BPAWorkQueue') IS NOT NULL ALTER TABLE BPMIQueueSnapshot DROP CONSTRAINT FK_BPMIQueueSnapshot_BPAWorkQueue IF object_id('FK_BPMIQueueTrend_BPAWorkQueue') IS NOT NULL ALTER TABLE BPMIQueueTrend DROP CONSTRAINT FK_BPMIQueueTrend_BPAWorkQueue IF object_id('FK_BPMIQueueInterimSnapshot_BPAWorkQueue') IS NOT NULL ALTER TABLE BPMIQueueInterimSnapshot DROP CONSTRAINT FK_BPMIQueueInterimSnapshot_BPAWorkQueue IF object_id('FK_BPMIConfiguredSnapshot_BPMISnapshotTrigger') IS NOT NULL ALTER TABLE BPMISnapshotTrigger DROP CONSTRAINT FK_BPMIConfiguredSnapshot_BPMISnapshotTrigger IF object_id('FK_BPASessionLog_Unicode_BPASession_pre65') IS NOT NULL ALTER TABLE BPASessionLog_Unicode_pre65 DROP CONSTRAINT FK_BPASessionLog_Unicode_BPASession_pre65 IF object_id('FK_BPASessionLog_NonUnicode_BPASession_pre65') IS NOT NULL ALTER TABLE BPASessionLog_NonUnicode_pre65 DROP CONSTRAINT FK_BPASessionLog_NonUnicode_BPASession_pre65 IF object_id('FK_BPAUserExternalIdentity_BPAUser') IS NOT NULL ALTER TABLE BPAUserExternalIdentity DROP CONSTRAINT FK_BPAUserExternalIdentity_BPAUser IF EXISTS (SELECT * FROM sysobjects where type='V' and id = OBJECT_ID(N'[vw_Audit]')) DROP VIEW [vw_Audit] IF EXISTS (SELECT * FROM sysobjects where type='V' and id = OBJECT_ID(N'[vw_Audit_improved]')) DROP VIEW [vw_Audit_improved] IF EXISTS (SELECT * FROM sysobjects where type='V' and id = OBJECT_ID(N'[vwBPACalendar]')) DROP VIEW [vwBPACalendar] IF EXISTS (SELECT * FROM sysobjects where type='V' and id = OBJECT_ID(N'[vwBPAUptime]')) DROP VIEW [vwBPAUptime] if exists (select * from sysobjects where type='V' and id = object_id('BPVWorkQueueItem')) drop view BPVWorkQueueItem; If object_id('BPViewWorkQueueItemTag') is not null drop view BPViewWorkQueueItemTag If object_id('BPViewWorkQueueItemTagBare') is not null drop VIEW BPViewWorkQueueItemTagBare if object_id('BPVSessionInfo') is not null drop view BPVSessionInfo; if object_id('BPVSession') is not null drop view BPVSession; if object_id('BPVAnnotatedScheduleLog') is not null drop view BPVAnnotatedScheduleLog; if object_id('BPVScriptEnvironment') is not null drop view BPVScriptEnvironment; if OBJECT_ID('ufn_GetReportDays') is not null drop function ufn_GetReportDays; if OBJECT_ID('ufn_GetReportMonths') is not null drop function ufn_GetReportMonths; if OBJECT_ID('ufn_GetQueueEvents') is not null drop function ufn_GetQueueEvents; IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[spBPAUpdateCalendar]') AND type in (N'P', N'PC')) DROP PROCEDURE [spBPAUpdateCalendar] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[spBPAUptimeMonth]') AND type in (N'P', N'PC')) DROP PROCEDURE [spBPAUptimeMonth] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_RefreshProductivityData]') AND type = N'P') DROP PROCEDURE [usp_RefreshProductivityData] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_RefreshUtilisationData]') AND type = N'P') DROP PROCEDURE [usp_RefreshUtilisationData] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_RefreshMI]') AND type = N'P') DROP PROCEDURE [usp_RefreshMI] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_CreateInterimQueueSnapshot]') AND type = N'P') DROP PROCEDURE [usp_CreateInterimQueueSnapshot] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_CreateFirstQueueSnapshot]') AND type = N'P') DROP PROCEDURE [usp_CreateFirstQueueSnapshot] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_CreateNextQueueSnapshot]') AND type = N'P') DROP PROCEDURE [usp_CreateNextQueueSnapshot] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_CalculateQueueTrends]') AND type = N'P') DROP PROCEDURE [usp_CalculateQueueTrends] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_TriggerQueueSnapshot]') AND type = N'P') DROP PROCEDURE [usp_TriggerQueueSnapshot] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_WorkforceAvailability]') AND type = N'P') DROP PROCEDURE [BPDS_WorkforceAvailability] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_TotalAutomations]') AND type = N'P') DROP PROCEDURE [BPDS_TotalAutomations] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_LargestTables]') AND type = N'P') DROP PROCEDURE [BPDS_LargestTables] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_DailyUtilisation]') AND type = N'P') DROP PROCEDURE [BPDS_DailyUtilisation] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_ProcessUtilisationByHour]') AND type = N'P') DROP PROCEDURE [BPDS_ProcessUtilisationByHour] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_ResourceUtilisationByHour]') AND type = N'P') DROP PROCEDURE [BPDS_ResourceUtilisationByHour] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_AverageHandlingTime]') AND type = N'P') DROP PROCEDURE [BPDS_AverageHandlingTime] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_DailyProductivity]') AND type = N'P') DROP PROCEDURE [BPDS_DailyProductivity] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_FTEProductivityComparison]') AND type = N'P') DROP PROCEDURE [BPDS_FTEProductivityComparison] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_AverageRetries]') AND type = N'P') DROP PROCEDURE [BPDS_AverageRetries] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_Exceptions]') AND type = N'P') DROP PROCEDURE [BPDS_Exceptions] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_QueueVolumesNow]') AND type = N'P') DROP PROCEDURE [BPDS_QueueVolumesNow] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[BPDS_QueueSnapshotComparison]') AND type = N'P') DROP PROCEDURE [BPDS_QueueSnapshotComparison] IF object_id('BPAMIControl') IS NOT NULL DROP TABLE BPAMIControl IF object_id('BPMIUtilisationShadow') IS NOT NULL DROP TABLE BPMIUtilisationShadow IF object_id('BPMIUtilisationDaily') IS NOT NULL DROP TABLE BPMIUtilisationDaily IF object_id('BPMIUtilisationMonthly') IS NOT NULL DROP TABLE BPMIUtilisationMonthly IF object_id('BPMIProductivityShadow') IS NOT NULL DROP TABLE BPMIProductivityShadow IF object_id('BPMIProductivityDaily') IS NOT NULL DROP TABLE BPMIProductivityDaily IF object_id('BPMIProductivityMonthly') IS NOT NULL DROP TABLE BPMIProductivityMonthly IF object_id('BPAGroupUserRolePerm') IS NOT NULL DROP TABLE BPAGroupUserRolePerm IF object_id('BPATreeDefaultGroup') IS NOT NULL DROP TABLE BPATreeDefaultGroup IF object_id('BPATreePerm') IS NOT NULL DROP TABLE BPATreePerm IF object_id('BPACredentialRole') IS NOT NULL DROP TABLE BPACredentialRole IF object_id('BPAResourceRole') IS NOT NULL DROP TABLE BPAResourceRole IF object_id('BPAUserRoleAssignment') IS NOT NULL DROP TABLE BPAUserRoleAssignment IF object_id('BPAUserRolePerm') IS NOT NULL DROP TABLE BPAUserRolePerm IF object_id('BPAUserRole') IS NOT NULL DROP TABLE BPAUserRole IF object_id('BPAUserExternalIdentity') IS NOT NULL DROP TABLE BPAUserExternalIdentity IF object_id('BPAPermGroupMember') IS NOT NULL DROP TABLE BPAPermGroupMember IF object_id('BPAPermGroup') IS NOT NULL DROP TABLE BPAPermGroup IF object_id('BPAPermScope') IS NOT NULL DROP TABLE BPAPermScope IF object_id('BPAScope') IS NOT NULL DROP TABLE BPAScope IF object_id('BPAPerm') IS NOT NULL DROP TABLE BPAPerm IF object_id('BPADataTracker') IS NOT NULL DROP TABLE BPADataTracker IF object_id('BPAExceptionType') IS NOT NULL DROP TABLE BPAExceptionType IF object_id('BPAInternalAuth') IS NOT NULL DROP TABLE BPAInternalAuth if object_id('BPAReleaseEntry') is not null drop table BPAReleaseEntry; if object_id('BPARelease') is not null drop table BPARelease; if object_id('BPAPackageProcessGroupMember') is not null drop table BPAPackageProcessGroupMember; if object_id('BPAPackageTile') is not null drop table BPAPackageTile; if object_id('BPAPackageDashboard') is not null drop table BPAPackageDashboard; if object_id('BPAPackageProcess') is not null drop table BPAPackageProcess; if object_id('BPAPackageWorkQueue') is not null drop table BPAPackageWorkQueue; if object_id('BPAPackageCredential') is not null drop table BPAPackageCredential; if object_id('BPAPackageSchedule') is not null drop table BPAPackageSchedule; if object_id('BPAPackageCalendar') is not null drop table BPAPackageCalendar; if object_id('BPAPackageScheduleList') is not null drop table BPAPackageScheduleList; if object_id('BPAPackageWebService') is not null drop table BPAPackageWebService; if object_id('BPAPackageEnvironmentVar') is not null drop table BPAPackageEnvironmentVar; if object_id('BPAPackageFont') is not null drop table BPAPackageFont; if object_id('BPAPackageWebApi') is not null drop table BPAPackageWebApi; if object_id('BPAPackage') is not null drop table BPAPackage; IF object_id('BPAGroupGroup') IS NOT NULL DROP TABLE BPAGroupGroup IF object_id('BPAGroupProcess') IS NOT NULL DROP TABLE BPAGroupProcess IF object_id('BPAGroupResource') IS NOT NULL DROP TABLE BPAGroupResource IF object_id('BPAGroupQueue') IS NOT NULL DROP TABLE BPAGroupQueue IF object_id('BPAGroupTile') IS NOT NULL DROP TABLE BPAGroupTile IF object_id('BPAGroupUser') IS NOT NULL DROP TABLE BPAGroupUser if object_id('BPACaseLock') is not null drop table BPACaseLock; IF object_id('BPAWorkQueueItemTag') IS NOT NULL DROP TABLE BPAWorkQueueItemTag IF object_id('BPATag') IS NOT NULL DROP TABLE BPATag IF object_id('BPAWorkQueueItem') IS NOT NULL DROP TABLE BPAWorkQueueItem if exists (select * from sys.foreign_keys where object_id = object_id(N'FK_BPASession_BPAWorkQueue') and parent_object_id = object_id(N'BPASession') ) alter table BPASession drop constraint FK_BPASession_BPAWorkQueue; IF object_id('BPAWorkQueue') IS NOT NULL DROP TABLE BPAWorkQueue IF object_id('BPAWorkQueueFilter') IS NOT NULL DROP TABLE BPAWorkQueueFilter IF object_id('BPAWorkQueueLog') IS NOT NULL DROP TABLE BPAWorkQueueLog IF object_id('BPASnapshotConfiguration') IS NOT NULL DROP TABLE BPASnapshotConfiguration IF object_id('BPMIConfiguredSnapshot') IS NOT NULL DROP TABLE BPMIConfiguredSnapshot IF object_id('BPMIQueueSnapshot') IS NOT NULL DROP TABLE BPMIQueueSnapshot IF object_id('BPMIQueueInterimSnapshot') IS NOT NULL DROP TABLE BPMIQueueInterimSnapshot IF object_id('BPMIQueueTrend') IS NOT NULL DROP TABLE BPMIQueueTrend IF object_id('BPMISnapshotTrigger') IS NOT NULL DROP TABLE BPMISnapshotTrigger IF object_id('BPAGroup') IS NOT NULL DROP TABLE BPAGroup IF object_id('BPATree') IS NOT NULL DROP TABLE BPATree IF object_id('BPADataPipelineInput') IS NOT NULL DROP TABLE BPADataPipelineInput IF object_id('BPADataPipelineProcess') IS NOT NULL DROP TABLE BPADataPipelineProcess IF object_id('BPADataPipelineProcessConfig') IS NOT NULL DROP TABLE BPADataPipelineProcessConfig IF object_id('BPADataPipelineSettings') IS NOT NULL DROP TABLE BPADataPipelineSettings IF object_id('BPADataPipelineOutputConfig') IS NOT NULL DROP TABLE BPADataPipelineOutputConfig IF object_id('BPADashboardTile') IS NOT NULL DROP TABLE BPADashboardTile IF object_id('BPADashboard') IS NOT NULL DROP TABLE BPADashboard IF object_id('BPATile') IS NOT NULL DROP TABLE BPATile IF object_id('BPATileDataSources') IS NOT NULL DROP TABLE BPATileDataSources IF object_id('BPAProcessMITemplate') IS NOT NULL DROP TABLE BPAProcessMITemplate if object_id('BPANonWorkingDay') is not null drop table BPANonWorkingDay; if object_id('BPAPublicHolidayWorkingDay') is not null drop table BPAPublicHolidayWorkingDay; if object_id('BPAScheduleTrigger') is not null drop table BPAScheduleTrigger; if object_id('BPACalendar') is not null drop table BPACalendar; if object_id('BPAValActionMap') is not null drop table BPAValActionMap; if object_id('BPAValCheck') is not null drop table BPAValCheck; if object_id('BPAValCategory') is not null drop table BPAValCategory; if object_id('BPAValType') is not null drop table BPAValType; if object_id('BPAValAction') is not null drop table BPAValAction; if object_id('BPAAlertEvent') is not null drop table BPAAlertEvent; if object_id('BPAScheduleAlert') is not null drop table BPAScheduleAlert; if object_id('BPAProcessAlert') is not null drop table BPAProcessAlert; if object_id('BPAEnvLock') is not null drop table BPAEnvLock; if object_id('BPAFont') is not null drop table BPAFont; IF object_id('BPACredentialsProcesses') IS NOT NULL DROP TABLE BPACredentialsProcesses IF object_id('BPACredentialsResources') IS NOT NULL DROP TABLE BPACredentialsResources IF object_id('BPACredentialsProperties') IS NOT NULL DROP TABLE BPACredentialsProperties IF object_id('BPACredentials') IS NOT NULL DROP TABLE BPACredentials if object_id('BPATaskProcess') is not null drop table BPATaskProcess; if object_id('BPATaskSession') is not null drop table BPATaskSession; if object_id('BPAScheduleLogEntry') is not null drop table BPAScheduleLogEntry; if object_id('BPAScheduleLog') is not null drop table BPAScheduleLog; if object_id('BPAScheduleListSchedule') is not null drop table BPAScheduleListSchedule; if object_id('BPAScheduleList') is not null drop table BPAScheduleList; if object_id('BPATask') is not null drop table BPATask; if object_id('BPASchedule') is not null drop table BPASchedule; if object_id('BPAPublicHolidayGroupMember') is not null drop table BPAPublicHolidayGroupMember; if object_id('BPAPublicHolidayGroup') is not null drop table BPAPublicHolidayGroup; if object_id('BPAPublicHoliday') is not null drop table BPAPublicHoliday; if object_id('BPAIntegerPref') is not null drop table BPAIntegerPref; if object_id('BPAStringPref') is not null drop table BPAStringPref; if object_id('BPAPref') is not null drop table BPAPref; IF object_id('BPAProcessEnvVar') IS NOT NULL DROP TABLE BPAProcessEnvVar IF object_id('BPAEnvironmentVar') IS NOT NULL DROP TABLE BPAEnvironmentVar IF object_id('BPAProcessGroupMembership') IS NOT NULL DROP TABLE BPAProcessGroupMembership IF object_id('BPAProcessGroup') IS NOT NULL DROP TABLE BPAProcessGroup if object_id('BPAScreenshot') is not null drop table BPAScreenshot; IF OBJECT_ID('BPADocumentProcessingQueueOverride') IS NOT NULL DROP TABLE [BPADocumentProcessingQueueOverride]; IF OBJECT_ID('BPADocumentTypeQueues') IS NOT NULL DROP TABLE [BPADocumentTypeQueues]; IF OBJECT_ID('BPADocumentTypeDefaultQueue') IS NOT NULL DROP TABLE [BPADocumentTypeDefaultQueue]; if exists (select * from sysobjects where id = object_id(N'[BPAAlert]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAAlert] if exists (select * from sysobjects where id = object_id(N'[BPAAlertEvent]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAAlertEvent] if exists (select * from sysobjects where id = object_id(N'[BPAAlertsMachines]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAAlertsMachines] if exists (select * from sysobjects where id = object_id(N'[BPAAliveResources]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAAliveResources] if exists (select * from sysobjects where id = object_id(N'[BPAAuditEvents]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAAuditEvents] if exists (select * from sysobjects where id = object_id(N'[BPACalendar]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPACalendar] if exists (select * from sysobjects where id = object_id(N'[BPAClock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAClock] if exists (select * from sysobjects where id = object_id(N'[BPAPermission]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAPermission] if exists (select * from sysobjects where id = object_id(N'[BPAProcessAttribute]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessAttribute] if exists (select * from sysobjects where id = object_id(N'[BPAUserViewPreferencePerProcess]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAUserViewPreferencePerProcess] if exists (select * from sysobjects where id = object_id(N'[BPARealTimeStatsView]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPARealTimeStatsView] if exists (select * from sysobjects where id = object_id(N'[BPAResourceAttribute]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAResourceAttribute] if exists (select * from sysobjects where id = object_id(N'[BPAResourceConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAResourceConfig] if exists (select * from sysobjects where id = object_id(N'[BPARole]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPARole] if exists (select * from sysobjects where id = object_id(N'[BPAStatistics]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAStatistics] if exists (select * from sysobjects where id = object_id(N'[BPAToolPosition]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAToolPosition] if exists (select * from sysobjects where id = object_id(N'[BPAWebServiceAsset]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAWebServiceAsset] if exists (select * from sysobjects where id = object_id(N'[BPAWebService]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAWebService] if exists (select * from sysobjects where id = object_id(N'[BPASession_OLD]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASession_OLD] if exists (select * from sysobjects where id = object_id(N'[BPASessionLog_OLD]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASessionLog_OLD] if exists (select * from sysobjects where id = object_id(N'[BPAProcessBackup]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessBackup] if exists (select * from sysobjects where id = object_id(N'[BPADBVersion]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPADBVersion] if exists (select * from sysobjects where id = object_id(N'[BPAProcessLock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessLock] if exists (select * from sysobjects where id = object_id(N'[BPARecent]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPARecent] if exists (select * from sysobjects where id = object_id(N'[BPAReport]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAReport] if exists (select * from sysobjects where id = object_id(N'[BPAResourceUnit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAResourceUnit] if exists (select * from sysobjects where id = object_id(N'[BPAScenarioLink]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAScenarioLink] if exists (select * from sysobjects where id = object_id(N'[BPASessionLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASessionLog] if exists (select * from sysobjects where id = object_id(N'[BPASessionLog_v4]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASessionLog_v4] if exists (select * from sysobjects where id = object_id(N'[BPASessionLog_NonUnicode]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASessionLog_NonUnicode] if exists (select * from sysobjects where id = object_id(N'[BPASessionLog_NonUnicode_pre65]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASessionLog_NonUnicode_pre65] if exists (select * from sysobjects where id = object_id(N'[BPASessionLog_Unicode]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASessionLog_Unicode] if exists (select * from sysobjects where id = object_id(N'[BPASessionLog_Unicode_pre65]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASessionLog_Unicode_pre65] if exists (select * from sysobjects where id = object_id(N'[BPASession]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASession] if exists (select * from sysobjects where id = object_id(N'[BPASysConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASysConfig] if exists (select * from sysobjects where id = object_id(N'[BPAUserPreference]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAUserPreference] if exists (select * from sysobjects where id = object_id(N'[BPAUserPrefNar]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAUserPrefNar] if exists (select * from sysobjects where id = object_id(N'[BPAUserRole]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAUserRole] if exists (select * from sysobjects where id = object_id(N'[BPAUserRoleNar]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAUserRoleNar] if exists (select * from sysobjects where id = object_id(N'[BPAScenarioDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAScenarioDetail] if exists (select * from sysobjects where id = object_id(N'[BPAScenario]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAScenario] if exists (select * from sysobjects where id = object_id(N'[BPAResource]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAResource] if exists (select * from sysobjects where id = object_id(N'[BPAWebSkillVersion]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAWebSkillVersion] if exists (select * from sysobjects where id = object_id(N'[BPASkillVersion]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASkillVersion] if exists (select * from sysobjects where id = object_id(N'[BPAProcessSkillDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessSkillDependency] if exists (select * from sysobjects where id = object_id(N'[BPASkill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPASkill] if exists (select * from sysobjects where id = object_id(N'[BPAProcessIDDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessIDDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessNameDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessNameDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessParentDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessParentDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessActionDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessActionDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessElementDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessElementDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessWebServiceDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessWebServiceDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessWebApiDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessWebApiDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessQueueDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessQueueDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessCredentialsDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessCredentialsDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessEnvironmentVarDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessEnvironmentVarDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessCalendarDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessCalendarDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcessFontDependency]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcessFontDependency] if exists (select * from sysobjects where id = object_id(N'[BPAProcess]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAProcess] if exists (select * from sysobjects where id = object_id(N'[BPALicenseActivationRequest]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPALicenseActivationRequest] if exists (select * from sysobjects where id = object_id(N'[BPALicense]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPALicense] if exists (select * from sysobjects where id = object_id(N'[BPAUser]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAUser] if exists (select * from sysobjects where id = object_id(N'[BPAPasswordRules]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAPasswordRules] if exists (select * from sysobjects where id = object_id(N'[BPAOldPassword]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAOldPassword] if exists (select * from sysobjects where id = object_id(N'[BPAPassword]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAPassword] if exists (select * from sysobjects where id = object_id(N'[BPAStatus]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAStatus] if exists (select * from sysobjects where id = object_id(N'[BPACacheETags]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPACacheETags] if exists (select * from sysobjects where id = object_id(N'[BPAKeyStore]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [BPAKeyStore] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_SetCacheETag]') AND type in (N'P', N'PC')) DROP PROCEDURE [usp_SetCacheETag] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_GetCacheETag]') AND type in (N'P', N'PC')) DROP PROCEDURE [usp_GetCacheETag] IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[usp_GetSchedule]') AND type in (N'P', N'PC')) DROP PROCEDURE [usp_GetSchedule] if exists (select * from sysobjects where id = object_id(N'BPAWebApiCustomOutputParameter') and objectproperty(id, N'IsUserTable') = 1) drop table BPAWebApiCustomOutputParameter; if exists (select * from sysobjects where id = object_id(N'BPAWebApiParameter') and objectproperty(id, N'IsUserTable') = 1) drop table BPAWebApiParameter; if exists (select * from sysobjects where id = object_id(N'BPAWebApiHeader') and objectproperty(id, N'IsUserTable') = 1) drop table BPAWebApiHeader; if exists (select * from sysobjects where id = object_id(N'BPAWebApiAction') and objectproperty(id, N'IsUserTable') = 1) drop table BPAWebApiAction; if exists (select * from sysobjects where id = object_id(N'BPAWebApiService') and objectproperty(id, N'IsUserTable') = 1) drop table BPAWebApiService; if exists (select * from sysobjects where id = object_id(N'BPASysWebUrlSettings') and objectproperty(id, N'IsUserTable') = 1) drop table BPASysWebUrlSettings; if exists (select * from sysobjects where id = object_id(N'BPASysWebConnectionSettings') and objectproperty(id, N'IsUserTable') = 1) drop table BPASysWebConnectionSettings; CREATE TABLE [BPADBVersion] ( [dbversion] [varchar] (50) COLLATE DATABASE_DEFAULT NOT NULL constraint PK_BPADBVersion primary key, [scriptrundate] [datetime] NULL , [scriptname] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [description] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE TABLE [BPAProcess] ( [processid] [uniqueidentifier] NOT NULL constraint PK_BPAProcess primary key, [name] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [description] [varchar] (1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [version] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [statusid] [int] NULL , [createdate] [datetime] NULL , [createdby] [uniqueidentifier] NULL , [lastmodifieddate] [datetime] NULL , [lastmodifiedby] [uniqueidentifier] NULL , [processxml] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE TABLE [BPAProcessLock] ( [processid] [uniqueidentifier] NOT NULL constraint PK_BPAProcessLock primary key, [lockdatetime] [datetime] NULL , [userid] [uniqueidentifier] NULL , [resourceid] [uniqueidentifier] NULL ) CREATE TABLE [BPARecent] ( [id] [uniqueidentifier] NOT NULL constraint PK_BPARecent primary key, [type] [int] NOT NULL , [datelastopened] [datetime] NOT NULL , [userid] [uniqueidentifier] NOT NULL , [name] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE TABLE [BPAReport] ( [reportid] [uniqueidentifier] NOT NULL constraint PK_BPAReport primary key, [name] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [description] [varchar] (1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [reportdata] [image] NULL ) CREATE TABLE [BPAResource] ( [resourceid] [uniqueidentifier] NOT NULL constraint PK_BPAResource primary key, [name] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [status] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [processesrunning] [int] NULL , [actionsrunning] [int] NULL , [unitsallocated] [int] NULL , [lastupdated] [datetime] NULL ) CREATE TABLE [BPAResourceUnit] ( [resourceunitid] [uniqueidentifier] NOT NULL constraint PK_BPAResourceUnit primary key, [name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [resourceid] [uniqueidentifier] NULL , [capabilities] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE TABLE [BPAScenario] ( [scenarioid] [uniqueidentifier] NOT NULL , [testnum] [numeric](18, 0) NOT NULL , [passed] [smallint] NULL , [scenariotext] [varchar] (1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [scenarionotes] [varchar] (1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , CONSTRAINT [PK_BPAScenario] PRIMARY KEY CLUSTERED ( [scenarioid], [testnum] ) ) CREATE TABLE [BPAScenarioLink] ( [scenarioid] [uniqueidentifier] NOT NULL , [processid] [uniqueidentifier] NOT NULL , [scenarioname] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [createdate] [datetime] NULL , [userid] [uniqueidentifier] NULL , CONSTRAINT [PK_BPAScenarioLink] PRIMARY KEY CLUSTERED ( [scenarioid], [processid] ) ) CREATE TABLE [BPASession] ( [sessionid] [uniqueidentifier] NOT NULL constraint PK_BPASession primary key, [startdatetime] [datetime] NULL , [enddatetime] [datetime] NULL , [processid] [uniqueidentifier] NULL , [starterresourceid] [uniqueidentifier] NULL , [starteruserid] [uniqueidentifier] NULL , [runningresourceid] [uniqueidentifier] NULL , [runningosusername] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [statusid] [int] NULL , [sessionstatexml] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE TABLE [BPASessionLog] ( [logid] [uniqueidentifier] NOT NULL constraint PK_BPASessionLog primary key, [sessionid] [uniqueidentifier] NULL , [seqnum] [int] NULL , [logdatetime] [datetime] NULL , [message] [varchar] (2000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE TABLE [BPAStatus] ( [statusid] [int] NOT NULL constraint PK_BPAStatus primary key, [type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [description] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE TABLE [BPASysConfig] ( [id] [int] NOT NULL constraint PK_BPASysConfig primary key, [maxnumconcproc] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [populateusernameusing] [int] NOT NULL ) CREATE TABLE [BPAUser] ( [userid] [uniqueidentifier] NOT NULL constraint PK_BPAUser primary key, [username] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [password] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [validfromdate] [datetime] NULL , [validtodate] [datetime] NULL , [passwordexpirydate] [datetime] NULL , [useremail] [varchar] (60) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE TABLE [BPAUserPreference] ( [userid] [uniqueidentifier] NOT NULL , [userprefid] [int] NOT NULL , CONSTRAINT [PK_BPAUserPreference] PRIMARY KEY CLUSTERED ( [userid], [userprefid] ) ) CREATE TABLE [BPAUserPrefNar] ( [userprefid] [int] NOT NULL constraint PK_BPAUserPrefNar primary key, [preference1] [bit] NOT NULL , [preference2] [bit] NOT NULL ) CREATE TABLE [BPAUserRole] ( [userid] [uniqueidentifier] NOT NULL , [roleid] [int] NOT NULL , CONSTRAINT [PK_BPAUserRole] PRIMARY KEY CLUSTERED ( [userid], [roleid] ) ) CREATE TABLE [BPAUserRoleNar] ( [roleid] [int] NOT NULL constraint PK_BPAUserRoleNar primary key, [description] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) ALTER TABLE [BPASysConfig] WITH NOCHECK ADD CONSTRAINT [DF_BPASysConfig_populateusernameusing] DEFAULT (0) FOR [populateusernameusing] ALTER TABLE [BPAProcess] ADD CONSTRAINT [FK_BPAProcess_BPAStatus] FOREIGN KEY ( [statusid] ) REFERENCES [BPAStatus] ( [statusid] ), CONSTRAINT [FK_BPAProcess_BPAUser] FOREIGN KEY ( [createdby] ) REFERENCES [BPAUser] ( [userid] ), CONSTRAINT [FK_BPAProcess_BPAUser1] FOREIGN KEY ( [lastmodifiedby] ) REFERENCES [BPAUser] ( [userid] ) ALTER TABLE [BPAProcessLock] ADD CONSTRAINT [FK_BPAProcessLock_BPAProcess] FOREIGN KEY ( [processid] ) REFERENCES [BPAProcess] ( [processid] ), CONSTRAINT [FK_BPAProcessLock_BPAResource] FOREIGN KEY ( [resourceid] ) REFERENCES [BPAResource] ( [resourceid] ), CONSTRAINT [FK_BPAProcessLock_BPAUser] FOREIGN KEY ( [userid] ) REFERENCES [BPAUser] ( [userid] ) alter table [BPAProcessLock] nocheck constraint [FK_BPAProcessLock_BPAProcess] ALTER TABLE [BPARecent] ADD CONSTRAINT [FK_BPARecent_BPAUser] FOREIGN KEY ( [userid] ) REFERENCES [BPAUser] ( [userid] ) ALTER TABLE [BPAResourceUnit] ADD CONSTRAINT [FK_BPAResourceUnit_BPAResource] FOREIGN KEY ( [resourceid] ) REFERENCES [BPAResource] ( [resourceid] ) ALTER TABLE [BPAScenarioLink] ADD CONSTRAINT [FK_BPAScenarioLink_BPAProcess] FOREIGN KEY ( [processid] ) REFERENCES [BPAProcess] ( [processid] ) ALTER TABLE [BPASession] ADD CONSTRAINT [FK_BPASession_BPAProcess] FOREIGN KEY ( [processid] ) REFERENCES [BPAProcess] ( [processid] ), CONSTRAINT [FK_BPASession_BPAResource] FOREIGN KEY ( [starterresourceid] ) REFERENCES [BPAResource] ( [resourceid] ), CONSTRAINT [FK_BPASession_BPAResource1] FOREIGN KEY ( [runningresourceid] ) REFERENCES [BPAResource] ( [resourceid] ), CONSTRAINT [FK_BPASession_BPAStatus] FOREIGN KEY ( [statusid] ) REFERENCES [BPAStatus] ( [statusid] ), CONSTRAINT [FK_BPASession_BPAUser] FOREIGN KEY ( [starteruserid] ) REFERENCES [BPAUser] ( [userid] ) alter table [BPASession] nocheck constraint [FK_BPASession_BPAStatus] ALTER TABLE [BPASessionLog] ADD CONSTRAINT [FK_BPASessionLog_BPASession] FOREIGN KEY ( [sessionid] ) REFERENCES [BPASession] ( [sessionid] ) alter table [BPASessionLog] nocheck constraint [FK_BPASessionLog_BPASession] ALTER TABLE [BPAUserPreference] ADD CONSTRAINT [FK_BPAUserPreference_BPAUser] FOREIGN KEY ( [userid] ) REFERENCES [BPAUser] ( [userid] ), CONSTRAINT [FK_BPAUserPreference_BPAUserPrefNar] FOREIGN KEY ( [userprefid] ) REFERENCES [BPAUserPrefNar] ( [userprefid] ) alter table [BPAUserPreference] nocheck constraint [FK_BPAUserPreference_BPAUser] alter table [BPAUserPreference] nocheck constraint [FK_BPAUserPreference_BPAUserPrefNar] ALTER TABLE [BPAUserRole] ADD CONSTRAINT [FK_BPAUserRole_BPAUser] FOREIGN KEY ( [userid] ) REFERENCES [BPAUser] ( [userid] ), CONSTRAINT [FK_BPAUserRole_BPAUserRoleNar] FOREIGN KEY ( [roleid] ) REFERENCES [BPAUserRoleNar] ( [roleid] ) alter table [BPAUserRole] nocheck constraint [FK_BPAUserRole_BPAUser] alter table [BPAUserRole] nocheck constraint [FK_BPAUserRole_BPAUserRoleNar]
GO
GO
insert into BPAStatus values (0,'RUN','Pending'); insert into BPAStatus values (1,'RUN','Running'); insert into BPAStatus values (2,'RUN','Failed'); insert into BPAStatus values (3,'RUN','Stopped'); insert into BPAStatus values (4,'RUN','Completed'); insert into BPAStatus values (6,'ENV','Test'); insert into BPAStatus values (7,'ENV','Live'); insert into BPAStatus values (8,'ENV','Archived'); insert into BPASysConfig values (1,'1',0); insert into BPAUserRoleNar values (1, 'System Manager'); insert into BPAUserRoleNar values (2, 'Process Studio'); insert into BPAUserRoleNar values (3, 'Test Lab'); insert into BPAUserRoleNar values (4, 'Control Room'); insert into BPAUserRoleNar values (5, 'Report Console'); insert into BPAUserPrefNar values (1, 1, 1); insert into BPAResource values (NewID(),HOST_NAME(),'','','','',''); insert into BPADBVersion values ('10',GETUTCDATE(),'db_createR10.sql UTC','Create base version of Blue Prism Database.'); alter table BPASysConfig add InstallInProgress bit null;
GO
if not exists (select 1 from BPADBVersion where dbversion='11') begin exec('CREATE TABLE [BPAStatistics] ( [sessionid] [uniqueidentifier] NOT NULL, [name] [varchar] (50) NOT NULL, [datatype] [varchar] (32) NULL, [value_text] [varchar] (255) NULL, [value_number] [float] NULL, [value_currency] [money] NULL, [value_date] [datetime] NULL, [value_flag] [bit] NULL, CONSTRAINT PK_BPAStatistics primary key (sessionid, name) ); insert into BPADBVersion values (''11'',GETUTCDATE(),''db_upgradeR11.sql UTC'',''Database amendments - added BPAStatistics'') ') end
if not exists (select 1 from BPADBVersion where dbversion='12') begin exec('ALTER TABLE [BPASession] WITH NOCHECK ADD startparamsxml text NULL, logginglevelsxml text NULL insert into BPADBVersion values (''12'',GETUTCDATE(),''db_upgradeR12.sql UTC'',''Database amendments - added to BPASession startparamsxml and logginlevelsxml'') ') end
if not exists (select 1 from BPADBVersion where dbversion='13') begin exec('CREATE TABLE BPAResourceConfig ( name varchar(128) NOT NULL, config text NULL ) ALTER TABLE BPAResourceConfig ADD CONSTRAINT PK_BPAResourceConfig PRIMARY KEY CLUSTERED ( name ) insert into BPADBVersion values (''13'',GETUTCDATE(),''db_upgradeR13.sql UTC'',''Database amendments - added BPAResourceConfig'') ') end
if not exists (select 1 from BPADBVersion where dbversion='14') begin exec('insert into BPAStatus values (5,''RUN'',''Debugging''); insert into BPADBVersion values (''14'',GETUTCDATE(),''db_upgradeR14.sql UTC'',''Database amendments - added debugging status to BPAStatus'') ') end
if not exists (select 1 from BPADBVersion where dbversion='15') begin exec('ALTER TABLE [BPAResource] WITH NOCHECK ADD availability [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL insert into BPADBVersion values (''15'',GETUTCDATE(),''db_upgradeR15.sql UTC'',''Database amendments - added resource availability support'') ') end
if not exists (select 1 from BPADBVersion where dbversion='16') begin exec('alter table [BPAStatistics] drop column value_currency insert into BPADBVersion values (''16'',GETUTCDATE(),''db_upgradeR16.sql UTC'',''Database amendments - removes currency field from BPAStatistics'') ') end
if not exists (select 1 from BPADBVersion where dbversion='17') begin exec('CREATE INDEX [Index_processID] ON [BPASession]([processid]) CREATE INDEX [Index_statusID] ON [BPASession]([statusid]) CREATE INDEX [Index_sessionID] ON [BPASessionLog]([sessionid]) insert into BPADBVersion values (''17'',GETUTCDATE(),''db_upgradeR17.sql UTC'',''Database amendments - adds index to SessionID field in BPASessionLog and StatusID & ProcessID in BPASession'') ') end
if not exists (select 1 from BPADBVersion where dbversion='18') begin exec('ALTER TABLE BPAUser ADD isdeleted BIT DEFAULT 0 insert into BPADBVersion values (''18'',GETUTCDATE(),''db_upgradeR18.sql UTC'',''Database amendments - adds a IsDeleted column to the BPAUser table'') ') end
if not exists (select 1 from BPADBVersion where dbversion='19') begin exec('UPDATE BPAUser SET isdeleted = 0 insert into BPADBVersion values (''19'',GETUTCDATE(),''db_upgradeR19.sql UTC'',''Database amendments - populates BPAUser.IsDeleted column with default value 0'') ') end
if not exists (select 1 from BPADBVersion where dbversion='20') begin exec('CREATE INDEX [Index_sessionID] ON [BPASessionLog]([sessionid], [seqnum]) with (DROP_EXISTING = on) insert into BPADBVersion values (''20'',GETUTCDATE(),''db_upgradeR20.sql UTC'',''Database amendments - adds seqnum to INDEX_SESSIONID in BPASESSIONLOG'') ') end
if not exists (select 1 from BPADBVersion where dbversion='21') begin exec('CREATE TABLE BPAClock ( [Hour] [smallint] NOT NULL , [Minute] [smallint] NOT NULL CONSTRAINT [PK_BPAClock] PRIMARY KEY CLUSTERED ( [Hour], [Minute] ) ) ')exec('')exec('INSERT INTO BPAClock VALUES(0, 0) INSERT INTO BPAClock VALUES(1, 1) INSERT INTO BPAClock VALUES(2, 2) INSERT INTO BPAClock VALUES(3, 3) INSERT INTO BPAClock VALUES(4, 4) INSERT INTO BPAClock VALUES(5, 5) INSERT INTO BPAClock VALUES(6, 6) INSERT INTO BPAClock VALUES(7, 7) INSERT INTO BPAClock VALUES(8, 8) INSERT INTO BPAClock VALUES(9, 9) INSERT INTO BPAClock VALUES(10, 10) INSERT INTO BPAClock VALUES(11, 11) INSERT INTO BPAClock VALUES(12, 12) INSERT INTO BPAClock VALUES(13, 13) INSERT INTO BPAClock VALUES(14, 14) INSERT INTO BPAClock VALUES(15, 15) INSERT INTO BPAClock VALUES(16, 16) INSERT INTO BPAClock VALUES(17, 17) INSERT INTO BPAClock VALUES(18, 18) INSERT INTO BPAClock VALUES(19, 19) INSERT INTO BPAClock VALUES(20, 20) INSERT INTO BPAClock VALUES(21, 21) INSERT INTO BPAClock VALUES(22, 22) INSERT INTO BPAClock VALUES(23, 23) INSERT INTO BPAClock VALUES(-1, 24) INSERT INTO BPAClock VALUES(-1, 25) INSERT INTO BPAClock VALUES(-1, 26) INSERT INTO BPAClock VALUES(-1, 27) INSERT INTO BPAClock VALUES(-1, 28) INSERT INTO BPAClock VALUES(-1, 29) INSERT INTO BPAClock VALUES(-1, 30) INSERT INTO BPAClock VALUES(-1, 31) INSERT INTO BPAClock VALUES(-1, 32) INSERT INTO BPAClock VALUES(-1, 33) INSERT INTO BPAClock VALUES(-1, 34) INSERT INTO BPAClock VALUES(-1, 35) INSERT INTO BPAClock VALUES(-1, 36) INSERT INTO BPAClock VALUES(-1, 37) INSERT INTO BPAClock VALUES(-1, 38) INSERT INTO BPAClock VALUES(-1, 39) INSERT INTO BPAClock VALUES(-1, 40) INSERT INTO BPAClock VALUES(-1, 41) INSERT INTO BPAClock VALUES(-1, 42) INSERT INTO BPAClock VALUES(-1, 43) INSERT INTO BPAClock VALUES(-1, 44) INSERT INTO BPAClock VALUES(-1, 45) INSERT INTO BPAClock VALUES(-1, 46) INSERT INTO BPAClock VALUES(-1, 47) INSERT INTO BPAClock VALUES(-1, 48) INSERT INTO BPAClock VALUES(-1, 49) INSERT INTO BPAClock VALUES(-1, 50) INSERT INTO BPAClock VALUES(-1, 51) INSERT INTO BPAClock VALUES(-1, 52) INSERT INTO BPAClock VALUES(-1, 53) INSERT INTO BPAClock VALUES(-1, 54) INSERT INTO BPAClock VALUES(-1, 55) INSERT INTO BPAClock VALUES(-1, 56) INSERT INTO BPAClock VALUES(-1, 57) INSERT INTO BPAClock VALUES(-1, 58) INSERT INTO BPAClock VALUES(-1, 59) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''21'', GETUTCDATE(), ''db_upgradeR21.sql UTC'', ''Database amendments - Create and populate base table for uptime report.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='22') begin exec('CREATE TABLE BPACalendar ( [Day] [smallint] NOT NULL , [Month] [smallint] NOT NULL , [Year] [smallint] NOT NULL CONSTRAINT [PK_BPABPACalendar] PRIMARY KEY CLUSTERED ( [Day], [Month], [Year] ) ) ')exec('')exec('INSERT INTO BPACalendar VALUES(1,1,2003) INSERT INTO BPACalendar VALUES(2,2,2004) INSERT INTO BPACalendar VALUES(3,3,2005) INSERT INTO BPACalendar VALUES(4,4,-1) INSERT INTO BPACalendar VALUES(5,5,-1) INSERT INTO BPACalendar VALUES(6,6,-1) INSERT INTO BPACalendar VALUES(7,7,-1) INSERT INTO BPACalendar VALUES(8,8,-1) INSERT INTO BPACalendar VALUES(9,9,-1) INSERT INTO BPACalendar VALUES(10,10,-1) INSERT INTO BPACalendar VALUES(11,11,-1) INSERT INTO BPACalendar VALUES(12,12,-1) INSERT INTO BPACalendar VALUES(13,-1,-1) INSERT INTO BPACalendar VALUES(14,-1,-1) INSERT INTO BPACalendar VALUES(15,-1,-1) INSERT INTO BPACalendar VALUES(16,-1,-1) INSERT INTO BPACalendar VALUES(17,-1,-1) INSERT INTO BPACalendar VALUES(18,-1,-1) INSERT INTO BPACalendar VALUES(19,-1,-1) INSERT INTO BPACalendar VALUES(20,-1,-1) INSERT INTO BPACalendar VALUES(21,-1,-1) INSERT INTO BPACalendar VALUES(22,-1,-1) INSERT INTO BPACalendar VALUES(23,-1,-1) INSERT INTO BPACalendar VALUES(24,-1,-1) INSERT INTO BPACalendar VALUES(25,-1,-1) INSERT INTO BPACalendar VALUES(26,-1,-1) INSERT INTO BPACalendar VALUES(27,-1,-1) INSERT INTO BPACalendar VALUES(28,-1,-1) INSERT INTO BPACalendar VALUES(29,-1,-1) INSERT INTO BPACalendar VALUES(30,-1,-1) INSERT INTO BPACalendar VALUES(31,-1,-1) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''22'', GETUTCDATE(), ''db_upgradeR22.sql UTC'', ''Database amendments - Create and populate base table for uptime report.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='23') begin exec('CREATE VIEW vwBPACalendar AS SELECT c.[Year], DATEPART(QUARTER,c.[Date]) AS [Quarter], c.[Month], DATEPART(WEEK,c.[Date]) AS [Week], c.[Day], c.[Date], DATENAME(MONTH, c.[Date]) AS MonthName, DATENAME(WEEKDAY, c.[Date]) AS DayName FROM ( SELECT dd.[Day], mm.[Month], yy.[Year], DATEADD(DAY, dd.[Day] - 1, DATEADD(MONTH, mm.[Month] - 1, DATEADD(YEAR, yy.[Year] - 1900, CAST(0 AS DATETIME)))) AS [Date] FROM BPACalendar dd CROSS JOIN BPACalendar mm CROSS JOIN BPACalendar yy WHERE yy.[Year] >= 0 AND mm.[Month] >= 0 AND DATEPART(MONTH, DATEADD(DAY, dd.[Day] - 1, DATEADD(MONTH, mm.[Month] - 1, DATEADD(YEAR, yy.[Year] - 1900, CAST(0 AS DATETIME)))) )=mm.[Month] ) c ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''23'', GETUTCDATE(), ''db_upgradeR23.sql UTC'', ''Database amendments - Create view for uptime report.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='24') begin exec('CREATE VIEW vwBPAUptime AS SELECT DISTINCT c.[year], c.[quarter], c.[month], c.[week], c.[day], c.[date], h.[hour], m.[minute], DATEADD(MINUTE, 60 * h.[hour] + m.[minute], c.[date]) AS [time], CASE ISNULL(CAST(SessionId AS VARCHAR(36)), '''') WHEN '''' THEN 0 ELSE 10 END AS uptime, CASE ISNULL(CAST(SessionId AS VARCHAR(36)), '''') WHEN '''' THEN 10 ELSE 0 END AS downtime, r.[name] AS resource, DATEADD(HOUR, 8, c.[date]) AS [start], DATEADD(HOUR, 18, c.[date]) AS [end], 10 AS segment FROM vwBPACalendar c CROSS JOIN BPAClock h CROSS JOIN BPAClock m CROSS JOIN BPAResource r LEFT OUTER JOIN BPASession s ON ( s.StartDateTime <= (DATEADD(MINUTE, 60 * h.[hour] + m.[minute] + 10, c.[date])) AND s.EndDateTime >= (DATEADD(MINUTE, 60 * h.[hour] + m.[minute], c.[date])) AND r.ResourceId = s.StarterResourceId ) WHERE h.[hour] >= 8 AND h.[hour] < 18 AND m.[minute] % 10 = 0 AND DATENAME(WEEKDAY, c.[date]) NOT IN (''SATURDAY'', ''SUNDAY'') ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''24'', GETUTCDATE(), ''db_upgradeR24.sql UTC'', ''Database amendments - Create view for uptime report.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='25') begin exec('CREATE PROCEDURE spBPAUpdateCalendar AS UPDATE BPACalendar SET [year] = [year] + 1 WHERE DATENAME(MONTH, GETDATE()) = ''JANUARY'' AND [year] > 0 AND NOT EXISTS ( SELECT [year] FROM BPACalendar WHERE [year] > DATEPART(YEAR, GETDATE()) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''25'', GETUTCDATE(), ''db_upgradeR25.sql UTC'', ''Database amendments - Create SP for uptime report.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='26') begin exec('CREATE PROCEDURE spBPAUptimeMonth @Year INT = -1 , @Month INT = -1 AS DECLARE @CurrentDate DATETIME DECLARE @Date DATETIME DECLARE @FirstOfMonth DATETIME DECLARE @LastOfMonth DATETIME DECLARE @StartWeek INT DECLARE @EndWeek INT DECLARE @StartYear INT DECLARE @EndYear INT DECLARE @MonthDiff INT DECLARE @CurrentYear INT DECLARE @CurrentMonth INT DECLARE @StartHour INT DECLARE @EndHour INT SET @StartHour = 9 SET @EndHour = 17 SET @CurrentDate = GETUTCDATE() SET @CurrentYear = DATEPART(YEAR, @CurrentDate) SET @CurrentMonth = DATEPART(MONTH, @CurrentDate) IF (@Year < 0) OR (@Month < 0) BEGIN SET @Date = @CurrentDate SET @Year = @CurrentYear SET @Month = @CurrentMonth END ELSE BEGIN IF @Year < @CurrentYear SET @MonthDiff = 12 * (@CurrentYear - @Year - 1) - @CurrentMonth - (12 - @Month) ELSE IF @Year > @CurrentYear SET @MonthDiff = 12 * (@Year - @CurrentYear - 1) + @Month + (12 - @CurrentMonth) ELSE SET @MonthDiff = @Month - @CurrentMonth SET @Date = DATEADD(MONTH, @MonthDiff, @CurrentDate) END SET @FirstOfMonth = DATEADD(DAY, 1 - DATEPART(DAY, @Date), @Date) SET @LastOfMonth = DATEADD(DAY, -1, DATEADD(MONTH, 1, @FirstOfMonth)) IF (@Month = 1 AND DATENAME(WEEKDAY, @FirstOfMonth) IN (''TUESDAY'', ''WEDNESDAY'', ''THURSDAY'', ''FRIDAY'')) BEGIN SET @StartYear = @Year - 1 SET @StartWeek = DATEPART(WEEK, DATEADD(DAY, -1, @FirstOfMonth)) END ELSE BEGIN SET @StartYear = @Year SET @StartWeek = DATEPART(WEEK, @FirstOfMonth) END IF (@Month = 12 AND DATENAME(WEEKDAY, @LastOfMonth) IN (''MONDAY'', ''TUESDAY'', ''WEDNESDAY'', ''THURSDAY'')) BEGIN SET @EndYear = @Year + 1 SET @EndWeek = 1 END ELSE BEGIN SET @EndYear = @Year SET @EndWeek = DATEPART(WEEK, @LastOfMonth) END IF (@Month > 0) BEGIN UPDATE BPACalendar SET [year] = @Year - 1 WHERE [Day] = 1 AND [Month] = 1 UPDATE BPACalendar SET [year] = @Year WHERE [Day] = 2 AND [Month] = 2 UPDATE BPACalendar SET [year] = @Year + 1 WHERE [Day] = 3 AND [Month] = 3 END CREATE TABLE #BPASessionTemp ( [SessionID] [uniqueidentifier] NOT NULL , [StartDateTime] [datetime] NULL , [EndDateTime] [datetime] NULL, StarterResourceId [uniqueidentifier] ) IF (@Month > 0) BEGIN INSERT INTO #BPASessionTemp SELECT [SessionID], [StartDateTime], CASE StatusId WHEN 2 THEN CASE DATEDIFF(DAY, [StartDateTime], ISNULL([EndDateTime], GETDATE())) WHEN 0 THEN ISNULL([EndDateTime], GETDATE()) ELSE DATEADD(HOUR, 1, [StartDateTime]) END ELSE ISNULL([EndDateTime], GETDATE()) END AS [EndDateTime], StarterResourceId FROM BPASession WHERE StatusId IN (1, 2, 3, 4) AND ((DATEPART(YEAR, StartDateTime)= @Year AND DATEPART(MONTH, StartDateTime)=@Month) OR (DATEPART(YEAR, StartDateTime)= @StartYear AND DATEPART(WEEK, StartDateTime) = @StartWeek) OR (DATEPART(YEAR, EndDateTime)= @EndYear AND DATEPART(WEEK, EndDateTime) = @EndWeek)) END SELECT DISTINCT c.[year], c.[quarter], c.[month], c.[week], c.[day], c.[date], h.[hour], m.[minute], DATEADD(MINUTE, 60 * h.[hour] + m.[minute], c.[date]) AS [time], CASE ISNULL(CAST(SessionID AS VARCHAR(36)), '''') WHEN '''' THEN 0 ELSE 10 END AS uptime, CASE ISNULL(CAST(SessionID AS VARCHAR(36)), '''') WHEN '''' THEN 10 ELSE 0 END AS downtime, r.[name] AS resource, DATEADD(HOUR, @StartHour, c.[date]) AS [start], DATEADD(HOUR, @EndHour, c.[date]) AS [end], 10 AS segment FROM vwBPACalendar c CROSS JOIN BPAClock h CROSS JOIN BPAClock m CROSS JOIN BPAResource r LEFT OUTER JOIN #BPASessionTemp s ON ( s.StartDateTime <= (DATEADD(MINUTE, 60 * h.[hour] + m.[minute] + 10, c.[date])) AND s.EndDateTime >= (DATEADD(MINUTE, 60 * h.[hour] + m.[minute], c.[date])) AND r.ResourceId = s.StarterResourceId ) WHERE h.[hour] >= @StartHour AND h.[hour] < @EndHour AND m.[minute] % 10 = 0 AND DATENAME(WEEKDAY, c.[date]) NOT IN (''SATURDAY'', ''SUNDAY'') AND( (c.[year]= @StartYear AND c.[week] = @StartWeek) OR (c.[year]= @EndYear AND c.[week] = @EndWeek) OR (c.[year]= @Year AND c.[month] = @Month ) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''26'', GETUTCDATE(), ''db_upgradeR26.sql UTC'', ''Database amendments - Create SP for uptime report.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='27') begin exec('IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = object_id(N''[BPAProcessBackup]'') AND OBJECTPROPERTY(id, N''IsUserTable'') = 1 ) DROP TABLE [BPAProcessBackup] CREATE TABLE [BPAProcessBackup] ( [processid] [uniqueidentifier] NOT NULL constraint PK_BPAProcessBackup primary key, [name] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [description] [varchar] (1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [version] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [statusid] [int] NULL , [createdate] [datetime] NULL , [createdby] [uniqueidentifier] NULL , [lastmodifieddate] [datetime] NULL , [lastmodifiedby] [uniqueidentifier] NULL , [processxml] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [backupdate] [datetime] NULL , [restoredate] [datetime] NULL , [backuplevel] [int] NULL ) ALTER TABLE BPASysconfig ADD autosaveinterval INT INSERT INTO BPADBVersion VALUES ( ''27'', GETUTCDATE(), ''db_upgradeR27.sql UTC'', ''Database amendments - CREATE TABLE BPAProcessBackup and ALTER TABLE BPASysConfig'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='28') begin exec('CREATE TABLE [BPAAuditEvents] ( [eventdatetime] [datetime] NOT NULL, [eventid] [int] IDENTITY (1, 1) NOT NULL , [sCode] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [sNarrative] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [gSrcUserID] [uniqueidentifier] NOT NULL , [gTgtUserID] [uniqueidentifier] NULL , [gTgtProcID] [uniqueidentifier] NULL , [gTgtResourceID] [uniqueidentifier] NULL, [comments] [varchar] (512) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [oldXML] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [newXML] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) create clustered index INDEX_BPAAuditEvents_eventdatetime on BPAAuditEvents(eventdatetime); ')exec('')exec('create view vw_Audit as SELECT TOP 100 PERCENT "BPAAuditEvents"."eventdatetime" as eventdatetime, "BPAAuditEvents"."eventid", "BPAAuditEvents"."sCode", s."username" as [source user], "BPAAuditEvents"."sNarrative", "BPAAuditEvents"."comments", t."username" as [target user], "BPAProcess"."name", r."Name" as [target resource] FROM "BPAAuditEvents" "BPAAuditEvents" LEFT OUTER JOIN "BPAProcess" "BPAProcess" ON "BPAAuditEvents"."gTgtProcID"="BPAProcess"."processid" LEFT OUTER JOIN "BPAUser" s ON "BPAAuditEvents"."gSrcUserID"= s."userid" LEFT OUTER JOIN "BPAUser" t ON "BPAAuditEvents"."gTgtUserID"= t."userid" LEFT OUTER JOIN "BPAResource" r ON "BPAAuditEvents"."gTgtResourceID" = r."ResourceID" ORDER BY eventdatetime ')exec('')exec('insert into BPADBVersion values (''28'',GETUTCDATE(),''db_upgradeR28.sql UTC'',''Database amendments - new audit log table and new view for log-viewing.'') ') end
if not exists (select 1 from BPADBVersion where dbversion='29') begin exec('if exists (select * from dbo.sysobjects where id = object_id(N''[BPAUserRole]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) drop table [BPAUserRole] ')exec('')exec('if exists (select * from dbo.sysobjects where id = object_id(N''[BPAUserRoleNar]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) drop table [BPAUserRoleNar] ')exec('')exec('if exists (select * from dbo.sysobjects where id = object_id(N''[BPAUserRole]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) drop table [BPARole] ')exec('')exec('if exists (select * from dbo.sysobjects where id = object_id(N''[BPAPermission]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) drop table [BPAPermission] ')exec('')exec('if not exists (select * from dbo.sysobjects where id = object_id(N''[BPARole]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) CREATE TABLE [BPARole] ( [RoleID] [bigint] NOT NULL , [RoleName] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [RolePermissions] [bigint] NOT NULL , CONSTRAINT [PK_BPARole] PRIMARY KEY CLUSTERED ( [RoleID] ) ) ')exec('')exec('if not exists (select * from dbo.sysobjects where id = object_id(N''[BPAPermission]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) CREATE TABLE [BPAPermission] ( [PermissionID] [bigint] NOT NULL , [Name] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [PK_BPAPermission] PRIMARY KEY CLUSTERED ( [PermissionID] ) ) ')exec('')exec('IF NOT EXISTS (SELECT * FROM dbo.sysobjects O INNER JOIN SysColumns C ON O.ID=C.ID WHERE ObjectProperty(O.ID,''IsUserTable'')=1 AND O.Name=''BPAUser'' AND C.Name=''Roles'') ALTER TABLE BPAUser ADD Roles bigint NOT NULL DEFAULT 0 ')exec('')exec('IF NOT EXISTS (SELECT * FROM dbo.sysobjects O INNER JOIN SysColumns C ON O.ID=C.ID WHERE ObjectProperty(O.ID,''IsUserTable'')=1 AND O.Name=''BPAUser'' AND C.Name=''Permissions'') ALTER TABLE BPAUser ADD [Permissions] bigint NOT NULL DEFAULT 0 ')exec('')exec('if not ((select COUNT(*) from BPAPermission) > ''0'') begin INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (1, ''Create/Clone Process'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (2, ''Import Process'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (4, ''Edit Process'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (16, ''Delete Process'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (32, ''View Process'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (524288, ''Export Process'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (524343, ''Process Studio'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (64, ''Create Test Plan'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (128, ''Edit Test Plan'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (256, ''Clone Test Plan'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (512, ''Delete Test Plan'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (1024, ''Implement Test Plan'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (2048, ''View Test Plan Results'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (4096, ''Perform ad hoc Tests'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (8128, ''Test Lab'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (8192, ''Add Report'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (16384, ''Delete Report'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (32768, ''View Report'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (57344, ''Report Console'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (65536, ''Read-Only Access to Control Room'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (131072, ''Full Access to Control Room'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (196608, ''Control Room'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (262144, ''System Manager'') end ')exec('')exec('if not ((select COUNT(*) from bpaRole) > ''0'') begin INSERT INTO BPARole (RoleID, [RoleName], [RolePermissions]) VALUES (''1'', ''System Administrator'', ''9223372036854775807'') INSERT INTO BPARole (RoleID, [RoleName], [RolePermissions]) VALUES (''2'', ''Designer'', ''524343'') INSERT INTO BPARole (RoleID, [RoleName], [RolePermissions]) VALUES (''4'', ''Tester'', ''8128'') INSERT INTO BPARole (RoleID, [RoleName], [RolePermissions]) VALUES (''8'', ''Controller'', ''196608'') INSERT INTO BPARole (RoleID, [RoleName], [RolePermissions]) VALUES (''16'', ''Observer'', ''57344'') end ')exec('')exec('UPDATE BPAUser SET [Permissions]=''1048567'' where username=''admin'' ')exec('')exec('insert into BPADBVersion values (''29'',GETUTCDATE(),''db_upgradeR29.sql UTC'',''Database amendments - new user roles tables etc.'') ') end
if not exists (select 1 from BPADBVersion where dbversion='30') begin exec('IF (SELECT COUNT(a.Seqnum) FROM (SELECT TOP 1 Seqnum FROM BPASESSIONLOG) a) = 0 BEGIN drop table bpasessionlog CREATE TABLE [BPASessionLog] ( [logid] [uniqueidentifier] NOT NULL , [sessionid] [uniqueidentifier] NULL , [seqnum] [int] NULL , [StageID] [uniqueidentifier] NULL , [logdatetime] [datetime] NULL , [message] [varchar] (2000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) CREATE INDEX [Index_sessionID] ON [BPASessionLog]([sessionid], [seqnum]) ALTER TABLE [BPASessionLog] WITH NOCHECK ADD CONSTRAINT [PK_BPASessionLog] PRIMARY KEY CLUSTERED ( [logid] ) ALTER TABLE [BPASessionLog] ADD CONSTRAINT [FK_BPASessionLog_BPASession] FOREIGN KEY ( [sessionid] ) REFERENCES [BPASession] ( [sessionid] ) ALTER TABLE [BPASessionLog] NOCHECK CONSTRAINT [FK_BPASessionLog_BPASession] END INSERT INTO BPADBVersion VALUES ( ''30'', GETUTCDATE(), ''db_upgradeR30.sql UTC'', ''Database amendments - Add new stageid column to BPASessionLog.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='31') begin exec('alter table BPAAuditEvents add EditSummary TEXT ')exec('')exec('alter table bpasysconfig add EnforceEditSummaries Bit default 1 ')exec('')exec('update bpasysconfig set EnforceEditSummaries = ''1'' ')exec('')exec('alter table bpauser add UseEditSummaries Bit default 1 ')exec('')exec('update bpauser set UseEditSummaries = ''1'' ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''31'', GETUTCDATE(), ''db_upgradeR31.sql UTC'', ''Database amendments - Add new EnforceEditSummaries column to BPASysConfig; new column to BPAUser'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='32') begin exec('create table BPAAliveResources ( ResourceID [uniqueidentifier] NOT NULL , UserID [uniqueidentifier], LastUpdated [datetime], CONSTRAINT PK_BPAAliveResources PRIMARY KEY CLUSTERED ( [ResourceID] ) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''32'', GETUTCDATE(), ''db_upgradeR32.sql UTC'', ''Database amendments - Add new table BPAAliveResources showing who is logged on where to prevent the deletion of logged in users.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='33') begin exec('CREATE TABLE BPAScenarioDetail ( scenarioid uniqueidentifier NOT NULL, testnum numeric(18, 0) NOT NULL, detailid numeric(18, 0) NOT NULL, testtext varchar(1000) NULL ) ')exec('')exec('ALTER TABLE BPAScenarioDetail ADD CONSTRAINT PK_BPAScenarioDetail PRIMARY KEY CLUSTERED ( scenarioid, testnum, detailid ) ')exec('')exec('ALTER TABLE BPAScenarioDetail ADD CONSTRAINT FK_BPAScenarioDetail_BPAScenario FOREIGN KEY ( scenarioid, testnum ) REFERENCES BPAScenario ( scenarioid, testnum ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''33'', GETUTCDATE(), ''db_upgradeR33.sql UTC'', ''Database amendments - Add new table BPAScenarioDetail containing details outlining each test.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='34') begin exec('create table BPARealTimeStatsView ( ViewID uniqueidentifier, ProcessID uniqueidentifier, Flipped bit NOT NULL, DataItemsList TEXT, BoldValues TEXT, CONSTRAINT [PK_BPARealTimeStatsView] PRIMARY KEY CLUSTERED ( [ViewID] ), CONSTRAINT [FK_BPAProcess] FOREIGN KEY ( [ProcessID] ) REFERENCES BPAProcess ( [ProcessID] ) ) ')exec('')exec('if exists (select * from dbo.sysobjects where id = object_id(N''[BPAUserViewPreferencePerProcess]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) drop table [BPAUserViewPreferencePerProcess] ')exec('')exec('create table BPAUserViewPreferencePerProcess ( ProcessID uniqueidentifier, UserID uniqueidentifier, ViewID uniqueidentifier, CONSTRAINT [PK_BPAUserViewPreferencePerProcess] PRIMARY KEY CLUSTERED ( [ProcessID], [UserID] ), CONSTRAINT [FK_BPAUserViewPreferencePerProcess_BPARealTimeStatsView] FOREIGN KEY ( [ViewID] ) REFERENCES BPARealTimeStatsView ( [ViewID] ) ) ')exec('')exec('alter table bpaprocess add DefaultRealTimeStatsView uniqueidentifier, CONSTRAINT [FK_BPAProcess_DefaultRealTimeStatsView] FOREIGN KEY ( [DefaultRealTimeStatsView] ) REFERENCES BPARealtimeStatsView ( [ViewID] ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''34'', GETUTCDATE(), ''db_upgradeR34.sql UTC'', ''Database amendments - New tables and updates to cover View Preferences in realtime stats.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='35') begin exec('ALTER TABLE BPAUser ADD preferredStatisticsInterval VARCHAR(64) INSERT INTO BPADBVersion VALUES ( ''35'', GETUTCDATE(), ''db_upgradeR35.sql UTC'', ''Database amendments - Update BPAUser to allow preferred statistics interval..'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='36') begin exec('alter table BPASysconfig add ArchivingInterval VARCHAR(32), ArchivingTime smalldatetime, ArchivingDayOfMonth VARCHAR(32), ArchivingMinLogAgeLimit VARCHAR(32), ArchivingMachineID uniqueidentifier, ArchiveInProgress VARCHAR(20), CONSTRAINT [FK_BPASysconfig_BPAResource] FOREIGN KEY ( ArchivingMachineID ) REFERENCES BPAResource ( ResourceID ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''36'', GETUTCDATE(), ''db_upgradeR36.sql UTC'', ''Database amendments - Update BPASysconfig to store archiving settings.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='37') begin exec('ALTER TABLE [BPAProcessBackup] ADD [user_informed] [bit] NOT NULL CONSTRAINT [DF_BPAProcessBackup_user_informed] DEFAULT (0) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''37'', GETUTCDATE(), ''db_upgradeR37.sql UTC'', ''Database amendments - Alter BPAProcessBackup to store user_informed flag.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='38') begin exec('alter table [BPAProcessLock] check constraint [FK_BPAProcessLock_BPAProcess] ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''38'', GETUTCDATE(), ''db_upgradeR37.sql UTC'', ''Database amendments - Make sure foreign key constraint FK_BPAPROCESSLOCK_BPAPROCESS is enforced.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='39') begin exec('alter table bpasysconfig add PassWordExpiryWarningInterval tinyint ')exec('')exec('update bpasysconfig set PassWordExpiryWarningInterval = ''3'' INSERT INTO BPADBVersion VALUES ( ''39'', GETUTCDATE(), ''db_upgradeR39.sql UTC'', ''Database amendments - Add system preference allowing administrators to remind users of forthcoming password expiries.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='40') begin exec('Alter table [BPAStatus] Alter Column [type] [varchar] (10) COLLATE DATABASE_DEFAULT NOT NULL ')exec('')exec('Alter table [BPAStatus] Alter Column [description] [varchar] (20) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPASysConfig] Alter Column [maxnumconcproc] [varchar] (100) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAUser] Alter Column [username] [varchar] (20) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAUser] Alter Column [password] [varchar] (100) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAUser] Alter Column [useremail] [varchar] (60) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('IF object_id(''PK_BPAStatistics'') IS NULL BEGIN Alter table [BPAStatistics] Alter Column [name] [varchar] (50) COLLATE DATABASE_DEFAULT NULL; Alter table [BPAStatistics] Alter Column [datatype] [varchar] (32) COLLATE DATABASE_DEFAULT NULL; Alter table [BPAStatistics] Alter Column [value_text] [varchar] (255) COLLATE DATABASE_DEFAULT NULL; END ')exec('')exec('Alter table [BPAProcessBackup] Alter Column [name] [varchar] (128) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAProcessBackup] Alter Column [description] [varchar] (1000) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAProcessBackup] Alter Column [version] [varchar] (20) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('declare @InError bit set @InError =0 begin transaction exec (''Alter table [BPAProcessBackup] add [____temp] [text]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAProcessBackup] set [____temp] =[processxml]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAProcessBackup] drop column [processxml]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAProcessBackup] add [processxml] [text] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAProcessBackup] set [processxml] = [____temp] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''alter table [BPAProcessBackup] drop column [____temp]'') if @@error<>0 set @InError =1 if @@error = 0 commit transaction else rollback transaction ')exec('')exec('Alter table [BPAAuditEvents] Alter Column [sCode] [varchar] (10) COLLATE DATABASE_DEFAULT NOT NULL ')exec('')exec('Alter table [BPAAuditEvents] Alter Column [sNarrative] [varchar] (500) COLLATE DATABASE_DEFAULT NOT NULL ')exec('')exec('Alter table [BPAAuditEvents] Alter Column [comments] [varchar] (512) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('declare @InError bit set @InError =0 begin transaction exec (''Alter table [BPAAuditEvents] add [____temp] [text]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAAuditEvents] set [____temp] =[oldXML]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAAuditEvents] drop column [oldXML]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAAuditEvents] add [oldXML] [text] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAAuditEvents] set [oldXML] = [____temp] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''alter table [BPAAuditEvents] drop column [____temp]'') if @@error<>0 set @InError =1 if @@error = 0 commit transaction else rollback transaction ')exec('')exec('declare @InError bit set @InError =0 begin transaction exec (''Alter table [BPAAuditEvents] add [____temp] [text]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAAuditEvents] set [____temp] =[newXML]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAAuditEvents] drop column [newXML]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAAuditEvents] add [newXML] [text] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAAuditEvents] set [newXML] = [____temp] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''alter table [BPAAuditEvents] drop column [____temp]'') if @@error<>0 set @InError =1 if @@error = 0 commit transaction else rollback transaction ')exec('')exec('Alter table [BPARole] Alter Column [RoleName] [varchar] (100) COLLATE DATABASE_DEFAULT NOT NULL ')exec('')exec('Alter table [BPAPermission] Alter Column [Name] [varchar] (100) COLLATE DATABASE_DEFAULT NOT NULL ')exec('')exec('Alter table [BPADBVersion] Alter Column [dbversion] [varchar] (50) COLLATE DATABASE_DEFAULT NOT NULL ')exec('')exec('Alter table [BPADBVersion] Alter Column [scriptname] [varchar] (50) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPADBVersion] Alter Column [description] [varchar] (200) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAProcess] Alter Column [name] [varchar] (128) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAProcess] Alter Column [description] [varchar] (1000) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAProcess] Alter Column [version] [varchar] (20) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('declare @InError bit set @InError =0 begin transaction exec (''Alter table [BPAProcess] add [____temp] [text]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAProcess] set [____temp] =[processxml]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAProcess] drop column [processxml]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAProcess] add [processxml] [text] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAProcess] set [processxml] = [____temp] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''alter table [BPAProcess] drop column [____temp]'') if @@error<>0 set @InError =1 if @@error = 0 commit transaction else rollback transaction ')exec('')exec('Alter table [BPARecent] Alter Column [name] [varchar] (128) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAReport] Alter Column [name] [varchar] (128) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAReport] Alter Column [description] [varchar] (1000) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAResource] Alter Column [name] [varchar] (128) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAResource] Alter Column [status] [varchar] (10) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAResource] Alter Column [availability] [varchar] (16) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAResourceUnit] Alter Column [name] [varchar] (50) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('declare @InError bit set @InError =0 begin transaction exec (''Alter table [BPAResourceUnit] add [____temp] [text]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAResourceUnit] set [____temp] =[capabilities]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAResourceUnit] drop column [capabilities]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPAResourceUnit] add [capabilities] [text] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPAResourceUnit] set [capabilities] = [____temp] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''alter table [BPAResourceUnit] drop column [____temp]'') if @@error<>0 set @InError =1 if @@error = 0 commit transaction else rollback transaction ')exec('')exec('Alter table [BPAScenario] Alter Column [scenariotext] [varchar] (1000) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAScenario] Alter Column [scenarionotes] [varchar] (1000) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPAScenarioLink] Alter Column [scenarioname] [varchar] (50) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('Alter table [BPASession] Alter Column [runningosusername] [varchar] (50) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('declare @InError bit set @InError =0 begin transaction exec (''Alter table [BPASession] add [____temp] [text]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPASession] set [____temp] =[sessionstatexml]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPASession] drop column [sessionstatexml]'') if @@error<>0 set @InError =1 if @@error = 0 exec (''Alter table [BPASession] add [sessionstatexml] [text] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''update [BPASession] set [sessionstatexml] = [____temp] '') if @@error<>0 set @InError =1 if @@error = 0 exec (''alter table [BPASession] drop column [____temp]'') if @@error<>0 set @InError =1 if @@error = 0 commit transaction else rollback transaction ')exec('')exec('Alter table [BPASessionLog] Alter Column [message] [varchar] (2000) COLLATE DATABASE_DEFAULT NULL ')exec('')exec('DROP VIEW vw_Audit ')exec('')exec('CREATE VIEW vw_Audit AS SELECT TOP 100 PERCENT "BPAAuditEvents"."eventdatetime" as eventdatetime, "BPAAuditEvents"."eventid", "BPAAuditEvents"."sCode", s."username" as [source user], "BPAAuditEvents"."sNarrative", "BPAAuditEvents"."comments", t."username" as [target user], "BPAProcess"."name", r."Name" as [target resource] FROM "BPAAuditEvents" "BPAAuditEvents" LEFT OUTER JOIN "BPAProcess" "BPAProcess" ON "BPAAuditEvents"."gTgtProcID"="BPAProcess"."processid" LEFT OUTER JOIN "BPAUser" s ON "BPAAuditEvents"."gSrcUserID"= s."userid" LEFT OUTER JOIN "BPAUser" t ON "BPAAuditEvents"."gTgtUserID"= t."userid" LEFT OUTER JOIN "BPAResource" r ON "BPAAuditEvents"."gTgtResourceID" = r."ResourceID" ORDER BY eventdatetime ')exec('')exec('DROP VIEW vwBPAUptime ')exec('')exec('CREATE VIEW vwBPAUptime AS SELECT DISTINCT c.[year], c.[quarter], c.[month], c.[week], c.[day], c.[date], h.[hour], m.[minute], DATEADD(MINUTE, 60 * h.[hour] + m.[minute], c.[date]) AS [time], CASE ISNULL(CAST(SessionId AS VARCHAR(36)), '''') WHEN '''' THEN 0 ELSE 10 END AS uptime, CASE ISNULL(CAST(SessionId AS VARCHAR(36)), '''') WHEN '''' THEN 10 ELSE 0 END AS downtime, r.[name] AS resource, DATEADD(HOUR, 8, c.[date]) AS [start], DATEADD(HOUR, 18, c.[date]) AS [end], 10 AS segment FROM vwBPACalendar c CROSS JOIN BPAClock h CROSS JOIN BPAClock m CROSS JOIN BPAResource r LEFT OUTER JOIN BPASession s ON ( s.StartDateTime <= (DATEADD(MINUTE, 60 * h.[hour] + m.[minute] + 10, c.[date])) AND s.EndDateTime >= (DATEADD(MINUTE, 60 * h.[hour] + m.[minute], c.[date])) AND r.ResourceId = s.StarterResourceId ) WHERE h.[hour] >= 8 AND h.[hour] < 18 AND m.[minute] % 10 = 0 AND DATENAME(WEEKDAY, c.[date]) NOT IN (''SATURDAY'', ''SUNDAY'') ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''40'', GETUTCDATE(), ''db_upgradeR40.sql UTC'', ''Database amendments - Correct collation on columns.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='41') begin exec('ALTER TABLE BPAREALTIMESTATSVIEW ADD InTables Bit DEFAULT 0 ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''41'', GETUTCDATE(), ''db_upgradeR41.sql UTC'', ''Database amendments - Correct collation on columns.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='42') begin exec('CREATE TABLE [BPAWebService] ( [serviceid] [uniqueidentifier] NOT NULL constraint PK_BPAWebService primary key, [enabled] [bit] NOT NULL , [servicename] [varchar] (128) NULL , [url] [varchar] (2083) NULL , [wsdl] [text] NULL , [settingsXML] [text] NULL ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''42'', GETUTCDATE(), ''db_upgradeR42.sql UTC'', ''Addition of Web Services Table'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='43') begin exec('IF (SELECT COUNT(eventdatetime) FROM bpaauditevents) = 0 BEGIN DECLARE @ProcessID uniqueidentifier DECLARE @ProcName varchar(256) DECLARE C1 CURSOR FOR SELECT ProcessID, Name FROM BPAProcess OPEN C1 FETCH NEXT FROM C1 INTO @ProcessID, @ProcName WHILE (@@FETCH_STATUS = 0) BEGIN INSERT INTO BPAAuditEvents (eventdatetime, sCode, gSrcUserID, gTgtProcID, sNarrative, newXML, EditSummary) SELECT GETDATE(), ''P008'', ''00000000-0000-0000-0000-000000000000'', @ProcessID, ''The process '''''' + @ProcName + '''''' was inherited from a version older than Automate 2.0.0'', ProcessXML, ''Process inherited from a version older than Automate 2.0.0'' FROM BPAProcess where ProcessID = @ProcessID FETCH NEXT FROM C1 INTO @ProcessID, @ProcName END CLOSE C1 DEALLOCATE C1 END ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''43'', GETUTCDATE(), ''db_upgradeR43.sql UTC'', ''Copying of existing processes into audit log table in order that they appear in the process history feature.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='44') begin exec('ALTER TABLE BPAProcess DROP CONSTRAINT FK_BPAProcess_BPAStatus ALTER TABLE BPAProcess DROP COLUMN StatusID ALTER TABLE BPAProcess ADD AttributeID int NOT NULL DEFAULT 0 ')exec('')exec('UPDATE BPAProcess SET AttributeID = 2 ')exec('')exec('CREATE TABLE BPAProcessAttribute ( AttributeID int NOT NULL, AttributeName VARCHAR(64) NOT NULL, CONSTRAINT [PK_BPAProcessStatus] PRIMARY KEY CLUSTERED ( [AttributeID] ) ) ')exec('')exec('INSERT INTO BPAProcessAttribute (AttributeID, AttributeName) VALUES (1, ''Retired'') INSERT INTO BPAProcessAttribute (AttributeID, AttributeName) VALUES (2, ''Live'') ')exec('')exec('ALTER TABLE BPAResource ADD AttributeID int NOT NULL DEFAULT 0 ')exec('')exec('CREATE TABLE BPAResourceAttribute ( AttributeID int NOT NULL, AttributeName VARCHAR(64) NOT NULL, CONSTRAINT [PK_BPAResourceStatus] PRIMARY KEY CLUSTERED ( [AttributeID] ) ) ')exec('')exec('INSERT INTO BPAResourceAttribute (AttributeID, AttributeName) VALUES (1, ''Retired'') ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''44'', GETUTCDATE(), ''db_upgradeR44.sql UTC'', ''Adds database support for process/resource retirement etc'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='45') begin exec('INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (8, ''Compare Processes'') UPDATE BPAPermission SET PermissionID = 524351 WHERE [Name] = ''Process Studio'' UPDATE BPAUser SET Roles = ''1'' WHERE UserName = ''admin'' INSERT INTO BPADBVersion VALUES ( ''45'', GETUTCDATE(), ''db_upgradeR45.sql UTC'', ''Adjusts roles/permissions settings to account for new process comparision feature'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='46') begin exec('DELETE FROM BPAPermission WHERE [Name] in (''Create Test Plan'', ''Edit Test Plan'', ''Clone Test Plan'', ''Delete Test Plan'', ''Implement Test Plan'', ''Perform ad hoc Tests'', ''View Test Plan Results'', ''Test Lab'') DELETE FROM BPARole WHERE RoleName = ''Tester'' INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (64, ''Test Process'') UPDATE BPAPermission SET PermissionID = (PermissionID + 64) WHERE [Name] = ''Process Studio'' UPDATE BPARole SET RolePermissions = (SELECT PermissionID FROM BPAPermission WHERE [Name] = ''Process Studio'') WHERE RoleName = ''Designer'' INSERT INTO BPADBVersion VALUES ( ''46'', GETUTCDATE(), ''db_upgradeR46.sql UTC'', ''Adjusts roles/permissions settings to account removal of test lab'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='47') begin exec('CREATE VIEW vw_Audit_improved AS SELECT TOP 100 PERCENT "BPAAuditEvents"."eventdatetime" as [Event Datetime], "BPAAuditEvents"."eventid" as [Event ID], "BPAAuditEvents"."sCode" as Code, s."username" as [By User], "BPAAuditEvents"."sNarrative" as Narrative, "BPAAuditEvents"."comments" as Comments, t."username" as [Target User], p."name" as [Target Process], r."Name" as [Target Resource] FROM "BPAAuditEvents" "BPAAuditEvents" LEFT OUTER JOIN "BPAProcess" p ON "BPAAuditEvents"."gTgtProcID"= p."processid" LEFT OUTER JOIN "BPAUser" s ON "BPAAuditEvents"."gSrcUserID"= s."userid" LEFT OUTER JOIN "BPAUser" t ON "BPAAuditEvents"."gTgtUserID"= t."userid" LEFT OUTER JOIN "BPAResource" r ON "BPAAuditEvents"."gTgtResourceID" = r."ResourceID" ORDER BY eventdatetime ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''47'', GETUTCDATE(), ''db_upgradeR47.sql UTC'', ''Add improved view for audit log viewer'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='48') begin exec('INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (1048576, ''Create/Clone Business Object'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (2097152, ''Edit Business Object'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (4194304, ''Test Business Object'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (8388608, ''Import Business Object'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (16777216, ''Export Business Object'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (33554432, ''Delete Business Object'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (67108864, ''View Business Object'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (134217728, ''Compare Business Objects'') INSERT INTO BPAPermission (PermissionID, [Name]) VALUES (267386880, ''Object Studio'') UPDATE BPARole SET RoleName = ''Process Designer'' WHERE RoleID = 2 ')exec('')exec('DECLARE @NextRole as int set @NextRole = 2 * (SELECT MAX(RoleID) FROM BPARole) INSERT INTO BPARole (RoleID, RoleName, RolePermissions) VALUES (@NextRole, ''Business Object Designer'', 267386880) INSERT INTO BPADBVersion VALUES ( ''48'', GETUTCDATE(), ''db_upgradeR48.sql UTC'', ''Add necessary user roles for new object studio features'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='49') begin exec('ALTER TABLE BPASESSION DROP CONSTRAINT FK_BPASESSION_BPAPROCESS ')exec('')exec('ALTER TABLE BPAPROCESSLOCK DROP CONSTRAINT FK_BPAProcessLock_BPAProcess ')exec('')exec('ALTER TABLE BPAREALTIMESTATSVIEW DROP CONSTRAINT FK_BPAPROCESS ')exec('')exec('ALTER TABLE BPASCENARIOLINK DROP CONSTRAINT FK_BPAScenarioLink_BPAProcess ')exec('')exec('CREATE TABLE #PROCESSES_TEMP ( [processid] [uniqueidentifier] NOT NULL , [name] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [description] [varchar] (1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [version] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [createdate] [datetime] NULL , [createdby] [uniqueidentifier] NULL , [lastmodifieddate] [datetime] NULL , [lastmodifiedby] [uniqueidentifier] NULL , [DefaultRealTimeStatsView] uniqueidentifier, [processxml] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [AttributeID] int NOT NULL DEFAULT 0, ) INSERT INTO #PROCESSES_TEMP SELECT * FROM BPAPROCESS DROP TABLE BPAPROCESS CREATE TABLE [BPAProcess] ( [processid] [uniqueidentifier] NOT NULL , [ProcessType] [VarChar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [name] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [description] [varchar] (1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [version] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [createdate] [datetime] NULL , [createdby] [uniqueidentifier] NULL , [lastmodifieddate] [datetime] NULL , [lastmodifiedby] [uniqueidentifier] NULL , [processxml] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [DefaultRealTimeStatsView] uniqueidentifier, [AttributeID] int NOT NULL DEFAULT 0, CONSTRAINT [PK_BPAProcess] PRIMARY KEY CLUSTERED ( [processid] ), CONSTRAINT [FK_BPAProcess_BPAUser] FOREIGN KEY ( [createdby] ) REFERENCES [BPAUser] ( [userid] ), CONSTRAINT [FK_BPAProcess_BPAUser1] FOREIGN KEY ( [lastmodifiedby] ) REFERENCES [BPAUser] ( [userid] ), CONSTRAINT [FK_BPAProcess_DefaultRealTimeStatsView] FOREIGN KEY ( [DefaultRealTimeStatsView] ) REFERENCES [BPARealTimeStatsView] ( [ViewID] ) ) INSERT INTO BPAPROCESS (ProcessID, ProcessType, [Name], Description, Version, CreateDate, CreatedBy, LastModifiedDate, LastModifiedBy, ProcessXMl, DefaultRealtimeStatsView, AttributeID) SELECT ProcessID, ''P'', [Name], Description, Version, CreateDate, CreatedBy, LastModifiedDate, LastModifiedBy, ProcessXMl, DefaultRealtimeStatsView, AttributeID FROM #PROCESSES_TEMP DROP TABLE #PROCESSES_TEMP ')exec('')exec('ALTER TABLE BPASESSION ADD CONSTRAINT [FK_BPASession_BPAProcess] FOREIGN KEY ( [processid] ) REFERENCES [BPAProcess] ( [processid] ) ')exec('')exec('ALTER TABLE BPAPROCESSLOCK ADD CONSTRAINT [FK_BPAProcessLock_BPAProcess] FOREIGN KEY ( [processid] ) REFERENCES [BPAProcess] ( [processid] ) ')exec('')exec('ALTER TABLE BPAREALTIMESTATSVIEW ADD CONSTRAINT [FK_BPAProcess] FOREIGN KEY ( [ProcessID] ) REFERENCES [BPAProcess] ( [processid] ) ')exec('')exec('ALTER TABLE BPASCENARIOLINK ADD CONSTRAINT [FK_BPAScenarioLink_BPAProcess] FOREIGN KEY ( [processid] ) REFERENCES [BPAProcess] ( [processid] ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''49'', GETUTCDATE(), ''db_upgradeR49.sql UTC'', ''Database amendments - Recreated process table with new process type field for business objects.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='50') begin exec('ALTER TABLE BPAProcessBackup ADD processtype VARCHAR(1) NULL ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''50'', GETUTCDATE(), ''db_upgradeR50.sql UTC'', ''Database amendments - add new process type field to process back up table.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='51') begin exec('CREATE TABLE [BPAToolPosition] ( [UserID] UNIQUEIDENTIFIER, [Name] [varchar] (100), [Position] [char] (1), [X] [int] NULL , [Y] [int] NULL , [Mode] [char] (1), [Visible] BIT NULL ) ')exec('')exec('ALTER TABLE BPAUser ADD SaveToolStripPositions BIT NULL ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''51'', GETUTCDATE(), ''db_upgradeR51.sql UTC'', ''Database amendments - create tool position table and add a save positions flag to user table.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='52') begin exec('ALTER TABLE BPAUser ADD PasswordDurationWeeks INTEGER NULL ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''52'', GETUTCDATE(), ''db_upgradeR52.sql UTC'', ''Database amendments - add a password duration column to user table.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='53') begin exec('INSERT INTO BPAPermission VALUES (128,''Subscribe to Process Alerts'') INSERT INTO BPAPermission VALUES (256,''Configure Process Alerts'') INSERT INTO BPAPermission VALUES (256+128,''Process Alerts'') INSERT INTO BPARole VALUES (64, ''Alert Subscriber'', 128 + 256) ALTER TABLE BPAUser ADD AlertEventTypes INTEGER NULL, AlertNotificationTypes INTEGER NULL CREATE TABLE [BPAAlertEvent] ( [AlertEventID] [int] IDENTITY (1, 1) NOT NULL , [AlertEventType] [int] NULL , [AlertNotificationType] [int] NULL , [Message] [varchar] (500) NULL , [ProcessID] [uniqueidentifier] NULL , [ResourceID] [uniqueidentifier] NULL , [SessionID] [uniqueidentifier] NULL , [Date] [datetime] NULL , [SubscriberUserID] [uniqueidentifier] NULL , [SubscriberResourceID] [uniqueidentifier] NULL , [SubscriberDate] [datetime] NULL , CONSTRAINT [PK_BPAAlertEvent] PRIMARY KEY CLUSTERED ( [AlertEventID] ) ) CREATE TABLE [BPAAlert] ( [UserID] [uniqueidentifier] NOT NULL , [ProcessID] [uniqueidentifier] NOT NULL , CONSTRAINT [PK_BPAAlert] PRIMARY KEY CLUSTERED ( [UserID], [ProcessID] ), CONSTRAINT [FK_BPAAlert_BPAProcess] FOREIGN KEY ( [ProcessID] ) REFERENCES [BPAProcess] ( [processid] ), CONSTRAINT [FK_BPAAlert_BPAUser] FOREIGN KEY ( [UserID] ) REFERENCES [BPAUser] ( [userid] ) ) INSERT INTO BPADBVersion VALUES ( ''53'', GETUTCDATE(), ''db_upgradeR53.sql UTC'', ''Process alerts changes: new columsn to BPAUser and new tables BPAAlert and BPAAlertEvent'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='54') begin exec('ALTER TABLE BPASysConfig ADD LicenseKey VARCHAR(64) ')exec('')exec('UPDATE BPASysConfig SET LicenseKey = ''MVcwc2sCCh8MZTFONGK0jp0='' ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''54'', GETUTCDATE(), ''db_upgradeR54.sql UTC'', ''Licensing changes: Added new LicenseKey field to BPASysConfig'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='55') begin exec('CREATE TABLE BPAAlertsMachines ( [MachineName] VARCHAR(128) NOT NULL UNIQUE, CONSTRAINT [PK_BPAAlertsMachines] PRIMARY KEY CLUSTERED ( [MachineName] ) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''55'', GETUTCDATE(), ''db_upgradeR55.sql UTC'', ''Licensing changes: Added new table for keeping track of the number of machines using process alerts.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='56') begin exec('DECLARE @SysMan BIGINT SELECT @SysMan = PermissionID FROM BPAPermission WHERE [Name]=''System Manager'' DECLARE @NewIndex BIGINT SET @NewIndex= 1 DECLARE @Count BIGINT DECLARE @Total BIGINT SET @Total = 0 SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''User Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''Report Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''Resource Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''Process Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''System Manager Logs'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''Web Service Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''Business Object Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''Database Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''General Settings'', @NewIndex) SET @Total = @Total + @NewIndex UPDATE BPAPermission SET PermissionID = @Total WHERE [Name] = ''System Manager'' DECLARE @MaxInt BIGINT SET @MaxInt = 9223372036854775807 UPDATE BPARole SET RolePermissions = ((RolePermissions & (@MaxInt ^ @SysMan)) | @Total) WHERE (RolePermissions & @SysMan) > 0 UPDATE BPAUser SET [Permissions] = (([Permissions] & (@MaxInt ^ @SysMan)) | @Total) WHERE ([Permissions] & @SysMan) > 0 UPDATE BPARole SET RolePermissions = @MaxInt WHERE RoleName=''System Administrator'' INSERT INTO BPADBVersion VALUES ( ''56'', GETUTCDATE(), ''db_upgradeR56.sql UTC'', ''Licensing changes: Added finer granularity of system manager permissions to allow tighter control over license key changes.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='57') begin exec('ALTER TABLE BPASession DROP CONSTRAINT FK_BPASession_BPAResource, CONSTRAINT FK_BPASession_BPAResource1, CONSTRAINT FK_BPASession_BPAStatus, CONSTRAINT FK_BPASession_BPAUser, CONSTRAINT FK_BPASession_BPAProcess ')exec('')exec('EXEC sp_rename ''BPASession.Index_processID'',''Index_processID_OLD'' EXEC sp_rename ''BPASession.Index_statusID'',''Index_statusID_OLD'' EXEC sp_rename ''PK_BPASession'',''PK_BPASession_OLD'' EXEC sp_rename ''BPASession'',''BPASession_OLD'' ')exec('')exec('ALTER TABLE BPASessionLog DROP CONSTRAINT FK_BPASessionLog_BPASession ')exec('')exec('EXEC sp_rename ''BPASessionLog.Index_sessionID'',''Index_sessionID_OLD'' EXEC sp_rename ''PK_BPASessionLog'',''PK_BPASessionLog_OLD'' EXEC sp_rename ''BPASessionLog'',''BPASessionLog_OLD'' ')exec('')exec('CREATE TABLE BPASession ( sessionid UNIQUEIDENTIFIER NOT NULL , sessionnumber INT IDENTITY (1, 1) NOT NULL , startdatetime DATETIME NULL , enddatetime DATETIME NULL , processid UNIQUEIDENTIFIER NULL , starterresourceid UNIQUEIDENTIFIER NULL , starteruserid UNIQUEIDENTIFIER NULL , runningresourceid UNIQUEIDENTIFIER NULL , runningosusername VARCHAR (50) , statusid INT NULL , startparamsxml TEXT , logginglevelsxml TEXT , sessionstatexml TEXT , CONSTRAINT PK_BPASession PRIMARY KEY CLUSTERED ( sessionid ), CONSTRAINT Index_sessionnumber UNIQUE NONCLUSTERED ( sessionnumber ), CONSTRAINT FK_BPASession_BPAProcess FOREIGN KEY ( processid ) REFERENCES BPAProcess ( processid ), CONSTRAINT FK_BPASession_BPAResource FOREIGN KEY ( starterresourceid ) REFERENCES BPAResource ( resourceid ), CONSTRAINT FK_BPASession_BPAResource1 FOREIGN KEY ( runningresourceid ) REFERENCES BPAResource ( resourceid ), CONSTRAINT FK_BPASession_BPAStatus FOREIGN KEY ( statusid ) REFERENCES BPAStatus ( statusid ), CONSTRAINT FK_BPASession_BPAUser FOREIGN KEY ( starteruserid ) REFERENCES BPAUser ( userid ) ) ALTER TABLE BPASession NOCHECK CONSTRAINT FK_BPASession_BPAStatus CREATE INDEX Index_processID ON BPASession(processid) CREATE INDEX Index_statusID ON BPASession(statusid) ')exec('')exec('CREATE TABLE BPASessionLog ( sessionnumber INT NOT NULL , seqnum INT NOT NULL , stageid UNIQUEIDENTIFIER NULL , stagename VARCHAR (50) NULL , stagetype INT NULL , processname VARCHAR (50) NULL , pagename VARCHAR (50) NULL , objectname VARCHAR (50) NULL , actionname VARCHAR (50) NULL , result TEXT NULL , resulttype INT NULL , startdatetime DATETIME NULL , enddatetime DATETIME NULL , attributexml TEXT NULL , CONSTRAINT PK_BPASessionLog PRIMARY KEY CLUSTERED ( sessionnumber, seqnum ), CONSTRAINT FK_BPASessionLog_BPASession FOREIGN KEY ( sessionnumber ) REFERENCES BPASession ( sessionnumber ) ) CREATE INDEX Index_SessionStageType ON BPASessionLog(stagetype, sessionnumber) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''57'', GETUTCDATE(), ''db_upgradeR57.sql UTC'', ''Amend session and log tables to work with session number rather than session id.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='58') begin exec('ALTER TABLE BPASessionLog ALTER COLUMN stagename VARCHAR(128) NULL ALTER TABLE BPASessionLog ALTER COLUMN processname VARCHAR(128) NULL ALTER TABLE BPASessionLog ALTER COLUMN pagename VARCHAR(128) NULL ALTER TABLE BPASessionLog ALTER COLUMN objectname VARCHAR(128) NULL ALTER TABLE BPASessionLog ALTER COLUMN actionname VARCHAR(128) NULL ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''58'', GETUTCDATE(), ''db_upgradeR58.sql UTC'', ''Amend session log table column sizes'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='59') begin exec('ALTER TABLE BPAUser ADD LogViewerHiddenColumns INT ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''59'', GETUTCDATE(), ''db_upgradeR59.sql UTC'', ''Add new user table column to control log viewer column visibility'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='60') begin exec('DROP TABLE BPAUserPreference DROP TABLE BPAUserPrefNar ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''60'', GETUTCDATE(), ''db_upgradeR60.sql UTC'', ''Database amendments - Drop unused tables BPAUserPreference and BPAUserPrefNar.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='61') begin exec('DROP TABLE BPAProcessBackup ')exec('')exec('CREATE TABLE [BPAProcessBackup] ( [processid] [uniqueidentifier] NOT NULL, [UserID] [uniqueidentifier] NOT NULL , [backupdate] [datetime] NULL , [processxml] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL , CONSTRAINT [PK_BPAProcessBackup] PRIMARY KEY CLUSTERED ( [processid] ), CONSTRAINT [FK_BPAProcessBackup_BPAProcess] FOREIGN KEY ( [processid] ) REFERENCES [BPAProcess] ( [processid] ), ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''61'', GETUTCDATE(), ''db_upgradeR61.sql UTC'', ''Database amendments - Simplify BPAProcessBackup table, and create the missing key constraints (bug 1529).'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='62') begin exec('ALTER TABLE [BPAResource] ADD Local BIT NOT NULL DEFAULT 0 ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''62'', GETUTCDATE(), ''db_upgradeR62.sql UTC'', ''Database amendments - added Local field to BPAResource (bug 3249).'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='63') begin exec('DROP TABLE BPAAliveResources ')exec('')exec('CREATE TABLE BPAAliveResources ( MachineName Varchar(16) NOT NULL, UserID uniqueidentifier NOT NULL, LastUpdated datetime NOT NULL, CONSTRAINT PK_BPAAliveResources PRIMARY KEY CLUSTERED ( [MachineName], [UserID] ), CONSTRAINT FK_BPAAliveResources FOREIGN KEY ( [UserID] ) REFERENCES [BPAUser] ( [UserID] ) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''63'', GETUTCDATE(), ''db_upgradeR63.sql UTC'', ''Database amendments - Remove relationship between BPAAliveResources and BPAResource tables.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='64') begin exec('IF object_id(''BPAUpgradeTempMachine'') IS NOT NULL DROP TABLE BPAUpgradeTempMachine CREATE TABLE BPAUpgradeTempMachine ( MachineName Varchar(16) primary key ) INSERT INTO BPAUpgradeTempMachine (MachineName) (SELECT TOP 1 R.[Name] AS MachineName FROM BPAResource R LEFT JOIN BPASysconfig C ON (C.ArchivingMachineID = R.ResourceID)) ')exec('')exec('ALTER TABLE BPASysconfig DROP FK_BPASysconfig_BPAResource ')exec('')exec('ALTER TABLE BPASysconfig ALTER COLUMN ArchivingMachineID VarChar(16) ')exec('')exec('EXEC sp_rename ''BPASysConfig.ArchivingMachineID'', ''ArchivingMachineName'', ''COLUMN'' ')exec('')exec('UPDATE BPASysConfig SET ArchivingMachineName=(SELECT MachineName FROM BPAUpgradeTempMachine) ')exec('')exec('DROP TABLE BPAUpgradeTempMachine INSERT INTO BPADBVersion VALUES ( ''64'', GETUTCDATE(), ''db_upgradeR64.sql UTC'', ''Database amendments - Remove relationship between BPASysConfig and BPAResource'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='65') begin exec('INSERT INTO BPAResourceAttribute (AttributeID, AttributeName) VALUES (2, ''Local'') INSERT INTO BPAResourceAttribute (AttributeID, AttributeName) VALUES (4, ''Debug'') UPDATE BPAResource SET AttributeID=(AttributeID | 2) WHERE [Local]=1 UPDATE BPAResource SET AttributeID=(AttributeID | 4) WHERE [Name] LIKE ''%\_debug'' ESCAPE ''\'' DECLARE @defname VARCHAR(100), @cmd VARCHAR(1000) SET @defname = ( SELECT default_constraints.name FROM sys.all_columns INNER JOIN sys.tables ON all_columns.object_id = tables.object_id INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id WHERE tables.name = ''BPAResource'' AND all_columns.name = ''Local'' ) SET @cmd = ''ALTER TABLE BPAResource DROP CONSTRAINT '' + @defname EXEC(@cmd) ALTER TABLE BPAResource DROP COLUMN [Local] DROP TABLE BPAResourceUnit INSERT INTO BPADBVersion VALUES ( ''65'', GETUTCDATE(), ''db_upgradeR65.sql UTC'', ''Database amendments - Add new AttributeID column to BPAResource, and remove redundant BPAResource.Local field in favour of using the AttributeID column. Also deleted BPAResourceUnit.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='66') begin exec('ALTER TABLE BPAUser ALTER COLUMN [UserName] VARCHAR(128) ALTER TABLE BPARole ADD SingleSignonUserGroup Varchar(256) ')exec('')exec('ALTER TABLE BPASysConfig ADD ActiveDirectoryProvider VarChar(4096) NOT NULL DEFAULT '''' ')exec('')exec('CREATE TABLE BPAInternalAuth ( UserID UNIQUEIDENTIFIER NOT NULL, Token UNIQUEIDENTIFIER NOT NULL, Expiry DATETIME NOT NULL, CONSTRAINT PK_BPAInternalAuth PRIMARY KEY CLUSTERED ( [Token] ), CONSTRAINT [FK_BPAInternalAuth_BPAUser] FOREIGN KEY ( [UserID] ) REFERENCES [BPAUser] ( [UserID] ) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''66'', GETUTCDATE(), ''db_upgradeR66.sql UTC'', ''Database amendments - Add new fields and table for single sign-on.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='67') begin exec('CREATE TABLE BPAWorkQueue ( id UNIQUEIDENTIFIER NOT NULL, name VARCHAR(30) UNIQUE NOT NULL, keyfield VARCHAR(30) NOT NULL, running BIT NOT NULL, maxattempts INT DEFAULT 0 NOT NULL, CONSTRAINT PK_BPAWorkQueue PRIMARY KEY (id), CONSTRAINT Index_name UNIQUE (name) ) ')exec('')exec('CREATE TABLE BPAWorkQueueItem ( id UNIQUEIDENTIFIER NOT NULL, queueid UNIQUEIDENTIFIER NOT NULL, resourceid UNIQUEIDENTIFIER DEFAULT NULL, keyvalue VARCHAR(30), status VARCHAR(30) DEFAULT '''', attempts INT DEFAULT 0, loaded DATETIME NULL, locked DATETIME NULL, completed DATETIME NULL, exception DATETIME NULL, exceptionreason TEXT NULL, deferred DATETIME, worktime INT DEFAULT 0, data TEXT NULL, CONSTRAINT PK_BPAWorkQueueItem PRIMARY KEY (id), CONSTRAINT FK_BPAWorkQueueItem_BPAWorkQueue FOREIGN KEY (queueid) REFERENCES BPAWorkQueue (id), CONSTRAINT FK_BPAWorkQueueItem_BPAResource FOREIGN KEY (resourceid) REFERENCES BPAResource (resourceid), ); CREATE INDEX Index_queueid ON BPAWorkQueueItem(queueid); CREATE INDEX Index_BPAWorkQueueItem_key ON BPAWorkQueueItem(keyvalue); CREATE INDEX Index_BPAWorkQueueItem_loaded ON BPAWorkQueueItem(loaded); CREATE INDEX Index_BPAWorkQueueItem_locked ON BPAWorkQueueItem(locked); CREATE INDEX Index_BPAWorkQueueItem_completed ON BPAWorkQueueItem(completed); CREATE INDEX Index_BPAWorkQueueItem_exception ON BPAWorkQueueItem(exception); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''67'', GETUTCDATE(), ''db_upgradeR67.sql UTC'', ''Added tables required for Work Queues development'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='68') begin exec('UPDATE BPAPermission SET [Name]=''Read-Only Access to Session Management'' WHERE [Name]=''Read-Only Access to Control Room'' UPDATE BPAPermission SET [Name]=''Full Access to Session Management'' WHERE [Name]=''Full Access to Control Room'' ')exec('')exec('DECLARE @NewIndex BIGINT SET @NewIndex= 1 DECLARE @Count BIGINT DECLARE @Total BIGINT SET @Total = 0 SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''Read-Only Access to Queue Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission ([Name],PermissionID) VALUES (''Full Access to Queue Management'', @NewIndex) SET @Total = @Total + @NewIndex SET @Total = @Total + (SELECT PermissionID FROM BPAPermission WHERE [Name]=''Read-Only Access to Session Management'') SET @Total = @Total + (SELECT PermissionID FROM BPAPermission WHERE [Name]=''Full Access to Session Management'') UPDATE BPAPermission SET PermissionID = @Total WHERE [Name]=''Control Room'' UPDATE BPARole SET RolePermissions = @Total WHERE RoleName=''Controller'' ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''68'', GETUTCDATE(), ''db_upgradeR68.sql UTC'', ''New permissions for Work Queue Management'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='69') begin exec('CREATE TABLE BPAExceptionType ( id UNIQUEIDENTIFIER NOT NULL, type VARCHAR(30) UNIQUE NOT NULL, constraint PK_BPAExceptionType primary key (id) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''69'', GETUTCDATE(), ''db_upgradeR69.sql UTC'', ''New table for exception types'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='70') begin exec('CREATE TABLE BPAWorkQueueFilter ( FilterID uniqueidentifier NOT NULL, FilterName VARCHAR(32) unique, FilterXML [TEXT] NOT NULL, CONSTRAINT [PK_BPAWorkQueueFilter] PRIMARY KEY CLUSTERED ( [FilterID] ) ) ')exec('')exec('ALTER TABLE BPAWorkQueue ADD DefaultFilterID uniqueidentifier NULL ')exec('')exec('ALTER TABLE BPAWorkQueue ADD CONSTRAINT [FK_BPAWorkQueue_BPAWorkQueueFilter] FOREIGN KEY ( [DefaultFilterID] ) REFERENCES [BPAWorkQueueFilter] ( [FilterID] ) INSERT INTO BPADBVersion VALUES ( ''70'', GETUTCDATE(), ''db_upgradeR70.sql UTC'', ''New table to store different filtered views of work queues'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='71') begin exec('CREATE TABLE [BPAProcessGroup] ( [GroupID] [uniqueidentifier] NOT NULL , [GroupName] [varchar] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , CONSTRAINT [PK_BPAProcessGroup] PRIMARY KEY CLUSTERED ( [GroupID] ), UNIQUE NONCLUSTERED ( [GroupName] ) ) CREATE TABLE [BPAProcessGroupMembership] ( [GroupID] [uniqueidentifier] NOT NULL , [ProcessID] [uniqueidentifier] NOT NULL , CONSTRAINT [PK_BPAProcessGroupMembership] PRIMARY KEY CLUSTERED ( [GroupID], [ProcessID] ), CONSTRAINT [FK_BPAProcessGroupMembership_BPAProcessGroup] FOREIGN KEY ( [GroupID] ) REFERENCES [BPAProcessGroup] ( [GroupID] ), CONSTRAINT [FK_BPAProcessGroupMembership_BPAProcess] FOREIGN KEY ( [ProcessID] ) REFERENCES [BPAProcess] ( [ProcessID] ), ) INSERT INTO BPADBVersion VALUES ( ''71'', GETUTCDATE(), ''db_upgradeR71.sql UTC'', ''Create new tables for organising processes into groups'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='72') begin exec('CREATE TABLE [BPAProcessMITemplate] ( [templatename] [varchar] (32) NOT NULL , [processid] [uniqueidentifier] NOT NULL , [defaulttemplate] [bit] NOT NULL, [templatexml] [text] NULL ) INSERT INTO BPADBVersion VALUES ( ''72'', GETUTCDATE(), ''db_upgradeR72.sql UTC'', ''Create a new table for storing process MI templates'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='73') begin exec('ALTER TABLE BPAWebService ADD timeout int default 10000; INSERT INTO BPADBVersion VALUES ( ''73'', GETUTCDATE(), ''db_upgradeR73.sql UTC'', ''Add timeout field to BPAWebService'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='74') begin exec('UPDATE BPAStatus set description=''Exception'' where description=''Failed''; INSERT INTO BPADBVersion VALUES ( ''74'', GETUTCDATE(), ''db_upgradeR74.sql UTC'', ''Change status description for Failed to Exception'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='75') begin exec('ALTER TABLE BPAProcess ADD compressedxml image NULL; ALTER TABLE BPAProcessBackup ADD compressedxml image NULL; ALTER TABLE BPASysConfig ADD CompressProcessXML bit DEFAULT 1 NOT NULL; ')exec('')exec('UPDATE BPASysConfig SET CompressProcessXML=1; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''75'', GETUTCDATE(), ''db_upgradeR75.sql UTC'', ''Changes to support Process XML compression'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='76') begin exec('CREATE TABLE BPACredentials ( id uniqueidentifier NOT NULL, name varchar(64) NOT NULL, description text NOT NULL, login varchar(64) NOT NULL, password varchar(64) NOT NULL, roleid bigint NULL, CONSTRAINT FK_BPACredentials_RoleID FOREIGN KEY ( roleid ) REFERENCES BPARole ( roleid ), CONSTRAINT PK_BPACredentials PRIMARY KEY CLUSTERED ( id ), CONSTRAINT Index_BPACredentials_name UNIQUE ( name ) ) ')exec('')exec('CREATE TABLE BPACredentialsProcesses ( credentialid uniqueidentifier NOT NULL, processid uniqueidentifier NOT NULL CONSTRAINT FK_BPACredentialsProcesses_cred FOREIGN KEY ( credentialid ) REFERENCES BPACredentials ( id ), CONSTRAINT FK_BPACredentialsProcesses_proc FOREIGN KEY ( processid ) REFERENCES BPAProcess ( processid ) ) ')exec('')exec('CREATE TABLE BPACredentialsResources ( credentialid uniqueidentifier NOT NULL, resourceid uniqueidentifier NOT NULL CONSTRAINT FK_BPACredentialsResources_cred FOREIGN KEY ( credentialid ) REFERENCES BPACredentials ( id ), CONSTRAINT FK_BPACredentialsResources_res FOREIGN KEY ( resourceid ) REFERENCES BPAResource ( resourceid ) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''76'', GETUTCDATE(), ''db_upgradeR76.sql UTC'', ''Create tables required for credentials management'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='77') begin exec('ALTER TABLE BPACredentials DROP CONSTRAINT FK_BPACredentials_RoleID ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''77'', GETUTCDATE(), ''db_upgradeR77.sql UTC'', ''Modify credentials table to allow assignment of multiple roles'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='78') begin exec('ALTER TABLE BPACredentialsProcesses ALTER COLUMN processid uniqueidentifier NULL ALTER TABLE BPACredentialsResources ALTER COLUMN resourceid uniqueidentifier NULL ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''78'', GETUTCDATE(), ''db_upgradeR78.sql UTC'', ''Modify credentials tables to allow an ''''any'''' for the resources and processes'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='79') begin exec('UPDATE BPAWebService SET timeout=10000 where timeout is NULL ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''79'', GETUTCDATE(), ''db_upgradeR79.sql UTC'', ''Resolve web service configuration entries with no timeout defined'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='80') begin exec('alter table BPAWorkQueueItem drop constraint FK_BPAWorkQueueItem_BPAWorkQueue; alter table BPAWorkQueue drop constraint PK_BPAWorkQueue; alter table BPAWorkQueue add ident int identity(1,1) not null; alter table BPAWorkQueue add constraint PK_BPAWorkQueue primary key (ident); alter table BPAWorkQueueItem add queueident int not null default 0; ')exec('')exec('update i set i.queueident = q.ident from BPAWorkQueueItem as i inner join BPAWorkQueue as q on i.queueid = q.id; alter table BPAWorkQueueItem add constraint FK_BPAWorkQueueItem_BPAWorkQueue foreign key (queueident) references BPAWorkQueue (ident); alter table BPAWorkQueueItem drop constraint PK_BPAWorkQueueItem; alter table BPAWorkQueueItem add ident bigint identity(1,1) not null; alter table BPAWorkQueueItem add constraint PK_BPAWorkQueueItem primary key (ident); ')exec('')exec('create nonclustered index INDEX_WorkQueueGuid on BPAWorkQueue(id); create nonclustered index INDEX_WorkQueueItemGuid on BPAWorkQueueItem(id) INSERT INTO BPADBVersion VALUES ( ''80'', GETUTCDATE(), ''db_upgradeR80.sql UTC'', ''Updated WorkQueue and WorkQueueItem tables to use an IDENTITY PK as well as a GUID'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='81') begin exec('alter table BPAResource drop column availability; INSERT INTO BPADBVersion VALUES ( ''81'', GETUTCDATE(), ''db_upgradeR81.sql UTC'', ''Drop unused availability column from BPAResource as per bug #3775'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='82') begin exec('if exists (select 1 from sysobjects where id = object_id(''bpa_sp_dropdefault'') and type=''P'') begin drop procedure bpa_sp_dropdefault end ')exec('')exec('create procedure bpa_sp_dropdefault @tableName varchar(256), @columnName varchar(256) as if exists (select 1 from syscolumns where id = object_id(@tableName) and name=@columnName) begin declare @defaultName varchar(256) select @defaultName = object_name(cdefault) from syscolumns where id = object_id(@tableName) and name = @columnName exec(''alter table ['' + @tableName + ''] drop constraint '' + @defaultName) end ')exec('')exec('alter table BPAWorkQueueItem drop constraint FK_BPAWorkQueueItem_BPAResource; exec bpa_sp_dropdefault ''BPAWorkQueueItem'', ''resourceid''; alter table BPAWorkQueueItem drop column resourceid; alter table BPAWorkQueueItem add sessionid uniqueidentifier null; INSERT INTO BPADBVersion VALUES ( ''82'', GETUTCDATE(), ''db_upgradeR82.sql UTC'', ''Updated work queue items to hold the session ID on being processed.'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='83') begin exec('alter table BPAWorkQueueItem add priority int not null default 0; ')exec('')exec('update BPAWorkQueueItem set priority=0 ')exec('')exec('create nonclustered index INDEX_WorkQueueItemPriority on BPAWorkQueueItem(priority) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''83'', GETUTCDATE(), ''db_upgradeR83.sql UTC'', ''Add priority field to BPAWOrkQueueItem'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='84') begin exec('ALTER TABLE BPASysConfig ADD credentialkey varchar(50); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''84'', GETUTCDATE(), ''db_upgradeR84.sql UTC'', ''Changes to support storing credential key in the DB'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='85') begin exec('create table BPAWorkQueueItemTag ( queueitemident bigint not null constraint FK_BPAWorkQueueItemTag_BPAWorkQueueItem foreign key references BPAWorkQueueItem (ident) on delete cascade, tag varchar(64) not null, primary key (queueitemident, tag) ) create index INDEX_WorkQueueItemTag_tag on BPAWorkQueueItemTag (tag) INSERT INTO BPADBVersion VALUES ( ''85'', GETUTCDATE(), ''db_upgradeR85.sql UTC'', ''Add tagging infrastructure to work queue items'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='86') begin exec('create table BPATag ( id int not null identity primary key, tag varchar(64) not null ); insert into BPATag (tag) select tag from BPAWorkQueueItemTag order by queueitemident; alter table BPAWorkQueueItemTag nocheck constraint all alter table BPAWorkQueueItemTag add tagid int constraint FK_BPAWorkQueueItemTag_BPATag foreign key references BPATag (id) on delete cascade; ')exec('')exec('update it set it.tagid = t.id from BPAWorkQueueItemTag as it inner join BPATag as t on it.tag = t.tag; alter table BPAWorkQueueItemTag alter column tagid int not null; alter table BPAWorkQueueItemTag check constraint all; drop index INDEX_WorkQueueItemTag_tag on BPAWorkQueueItemTag; declare @pkname varchar(64); select @pkname = name from sysobjects where xtype = ''PK'' and parent_obj = (object_id(''BPAWorkQueueItemTag'')); exec (''alter table BPAWorkQueueItemTag drop constraint [''+@pkname+'']''); alter table BPAWorkQueueItemTag add constraint PK_BPAWorkQueueItemTag primary key clustered (queueitemident, tagid); alter table BPAWorkQueueItemTag drop column tag; INSERT INTO BPADBVersion VALUES ( ''86'', GETUTCDATE(), ''db_upgradeR86.sql UTC'', ''Rework of the tagging infrastructure'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='87') begin exec('INSERT INTO BPAResourceAttribute (AttributeID, AttributeName) VALUES (8, ''Pool'') ALTER TABLE BPAResource ADD pool uniqueidentifier NULL; ALTER TABLE BPAResource ADD controller uniqueidentifier NULL; ')exec('')exec('create index INDEX_BPAResource_pool on BPAResource(pool) INSERT INTO BPADBVersion VALUES ( ''87'', GETUTCDATE(), ''db_upgradeR87.sql UTC'', ''Update tables for Resource Pools support'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='88') begin exec('sp_rename ''BPAWorkQueueItem.attempts'',''attempt'',''COLUMN'' ')exec('')exec('update BPAWorkQueueItem set attempt = attempt + 1 where exception is null and completed is null and locked is null; INSERT INTO BPADBVersion VALUES ( ''88'', GETUTCDATE(), ''db_upgradeR88.sql UTC'', ''BPAWorkQueueItem.attempts => attempt - represents attempt number, not number of attempts'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='89') begin exec('if exists (select * from sysobjects where type=''V'' and id = object_id(N''[vwBPACalendar]'')) drop view [vwBPACalendar]; if exists (select * from sysobjects where type=''V'' and id = object_id(N''[vwBPAUptime]'')) drop view [vwBPAUptime]; if exists (select * from sysobjects where id = object_id(N''[spBPAUpdateCalendar]'') and type in (N''P'', N''PC'')) drop procedure [spBPAUpdateCalendar]; if exists (select * from sysobjects where id = object_id(N''[spBPAUptimeMonth]'') and type in (N''P'', N''PC'')) drop procedure [spBPAUptimeMonth]; if exists (select * from sysobjects where id = object_id(N''[BPACalendar]'') and objectproperty(id, N''IsUserTable'') = 1) drop table [BPACalendar]; if exists (select * from sysobjects where id = object_id(N''[BPAClock]'') and objectproperty(id, N''IsUserTable'') = 1) drop table [BPAClock]; INSERT INTO BPADBVersion VALUES ( ''89'', GETUTCDATE(), ''db_upgradeR89.sql UTC'', ''Remove old Calendar / Clock tables and views'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='90') begin exec('create table BPAPublicHoliday ( id int not null constraint PK_BPAPublicHoliday primary key, name varchar(64) not null, dd int null, mm int null, dayofweek tinyint null constraint CHK_BPAPublicHoliday_dayofweek check (dayofweek < 7), nthofmonth int null constraint CHK_BPAPublicHoliday_nth check (nthofmonth > -2 and nthofmonth < 6), relativetoholiday int null constraint FK_BPAPublicHoliday_BPAPublicHoliday foreign key references BPAPublicHoliday(id) on delete no action, relativedaydiff int null, eastersunday bit null ); create table BPAPublicHolidayGroup ( id int not null identity constraint PK_BPAPublicHolidayGroup primary key, name varchar(64) not null constraint UNQ_BPAPublicHoliday_name unique ); create table BPAPublicHolidayGroupMember ( publicholidaygroupid int not null constraint FK_BPAPublicHolidayGroupMember_BPAPublicHolidayGroup foreign key references BPAPublicHolidayGroup(id) on delete cascade, publicholidayid int not null constraint FK_BPAPublicHolidayGroupMember_BPAPublicHoliday foreign key references BPAPublicHoliday(id) on delete cascade, constraint PK_BPAPublicHolidayGroupMember primary key (publicholidaygroupid, publicholidayid) ); insert into BPAPublicHoliday (id, name, dd, mm, dayofweek, nthofmonth, relativetoholiday, relativedaydiff, eastersunday) select 1, ''Easter Sunday'', null, null, null, null, null, null, 1 union all select 2, ''Christmas Day'', 25, 12, null, null, null, null, null union all select 3, ''New Years'''' Day'', 1, 1, null, null, null, null, null union all select 4, ''Second of January'', null, null, null, null, 3, 1, null union all select 5, ''St Patrick''''s Day'', 17, 3, null, null, null, null, null union all select 6, ''Good Friday'', null, null, null, null, 1, -2, null union all select 7, ''Easter Monday'', null, null, null, null, 1, 1, null union all select 8, ''May Day'', null, 5, 1, 1, null, null, null union all select 9, ''May Bank Holiday'', null, 5, 1, 1, null, null, null union all select 10, ''Spring Bank Holiday'', null, 5, 1, -1, null, null, null union all select 11, ''June Bank Holiday'', null, 6, 1, 1, null, null, null union all select 12, ''Orangemen''''s Day'', 12, 7, null, null, null, null, null union all select 13, ''August Bank Holiday'', null, 8, 1, 1, null, null, null union all select 14, ''Summer Bank Holiday'', null, 8, 1, 1, null, null, null union all select 15, ''Summer Bank Holiday'', null, 8, 1, -1, null, null, null union all select 16, ''October Bank Holiday'', null, 10, 1, -1, null, null, null union all select 17, ''St Andrew''''s Day'', 30, 11, null, null, null, null, null union all select 18, ''Boxing Day'', null, null, null, null, 2, 1, null ; declare @engName varchar(64), @scotName varchar(64), @norName varchar(64), @ireName varchar(64) set @engName=''England and Wales'' set @scotName=''Scotland'' set @norName=''Northern Ireland'' set @ireName=''Republic of Ireland'' insert into BPAPublicHolidayGroup (name) select @engName union select @scotName union select @norName union select @ireName; declare @england int, @scotland int, @northernIreland int, @eire int set @england = (select id from BPAPublicHolidayGroup where name=@engName); set @scotland = (select id from BPAPublicHolidayGroup where name=@scotName); set @northernIreland = (select id from BPAPublicHolidayGroup where name=@norName); set @eire = (select id from BPAPublicHolidayGroup where name=@ireName); insert into BPAPublicHolidayGroupMember (publicholidaygroupid, publicholidayid) select @england, 3 union all select @england, 6 union all select @england, 7 union all select @england, 8 union all select @england, 10 union all select @england, 15 union all select @england, 2 union all select @england, 18 union all select @scotland, 3 union all select @scotland, 4 union all select @scotland, 6 union all select @scotland, 8 union all select @scotland, 10 union all select @scotland, 14 union all select @scotland, 17 union all select @scotland, 2 union all select @scotland, 18 union all select @northernIreland, 3 union all select @northernIreland, 5 union all select @northernIreland, 6 union all select @northernIreland, 7 union all select @northernIreland, 8 union all select @northernIreland, 10 union all select @northernIreland, 12 union all select @northernIreland, 15 union all select @northernIreland, 2 union all select @northernIreland, 18 union all select @eire, 3 union all select @eire, 5 union all select @eire, 7 union all select @eire, 9 union all select @eire, 11 union all select @eire, 13 union all select @eire, 16 union all select @eire, 2 union all select @eire, 18 ; create table BPACalendar ( id int not null identity constraint PK_BPACalendar primary key, name varchar(64) not null constraint UNQ_BPACalendar_name unique, description text not null, publicholidaygroupid int null constraint FK_BPACalendar_BPAPublicHolidayGroup foreign key references BPAPublicHolidayGroup(id), workingweek tinyint not null constraint CHK_BPACalendar_workingweek check (workingweek < 128) ); create table BPANonWorkingDay ( calendarid int not null constraint FK_BPANonWorkingDay_BPACalendar foreign key references BPACalendar(id), nonworkingday datetime not null, constraint PK_BPANonWorkingDay primary key (calendarid, nonworkingday) ); create table BPAPublicHolidayWorkingDay ( calendarid int not null constraint FK_BPAPublicHolidayWorkingDay_BPACalendar foreign key references BPACalendar(id), publicholidayid int not null constraint FK_BPAPublicHolidayWorkingDay_BPAPublicHoliday foreign key references BPAPublicHoliday(id), constraint PK_BPAPublicHolidayWorkingDay primary key (calendarid, publicholidayid) ); insert into BPACalendar (name,description,workingweek) values (''Working Week / No Holidays'', ''Five day working week with no public holidays or other holidays'', ( 2 | 4 | 8 | 16 | 32 )); create table BPASchedule( id int not null identity constraint PK_BPASchedule primary key, name varchar(64) not null constraint UNQ_BPASchedule_name unique, description text not null, initialtaskid int null, retired bit not null constraint DEF_BPASchedule_retired default 0 ); create table BPATask( id int not null identity constraint PK_BPATask primary key, scheduleid int not null constraint FK_BPATask_BPASchedule foreign key references BPASchedule(id) on delete cascade, name varchar(64) not null constraint UNQ_BPATask_name unique, description text not null, onsuccess int null constraint FK_BPATask_BPATask_success foreign key references BPATask(id) on delete no action, onfailure int null constraint FK_BPATask_BPATask_failure foreign key references BPATask(id) on delete no action, constraint UNQ_BPATask_scheduleid_name UNIQUE (scheduleid, name) ); create table BPATaskProcess( taskid int not null constraint FK_BPATaskProcess_BPATask foreign key references BPATask(id) on delete cascade, processid uniqueidentifier not null constraint FK_BPATaskProcess_BPAProcess foreign key references BPAProcess(processid) on delete cascade, resourceid uniqueidentifier not null constraint FK_BPATaskProcess_BPAResource foreign key references BPAResource(resourceid) on delete cascade, failonerror bit not null constraint DEF_BPATaskProcess_failonerror default 1, processparams text null, constraint PK_BPATaskProcess primary key (taskid, processid, resourceid) ); create table BPAScheduleTrigger( id int not null identity constraint PK_BPAScheduleTrigger primary key, scheduleid int not null constraint FK_BPAScheduleTrigger_BPASchedule foreign key references BPASchedule(id) on delete cascade, priority int not null, mode tinyint not null, unittype tinyint not null constraint CHK_BPAScheduleTrigger check (unittype < 6), period int not null, startdate datetime not null, enddate datetime null, startpoint int null, endpoint int null, dayset int null, calendarid int null constraint FK_BPAScheduleTrigger_BPACalendar foreign key references BPACalendar(id), nthofmonth int null constraint CHK_BPAScheduleTrigger_nthofmonth check (nthofmonth > -2 and nthofmonth < 6), missingdatepolicy tinyint null constraint CHK_BPAScheduleTrigger_missingdatepolicy check (missingdatepolicy < 3) ); create table BPAScheduleLog ( id int not null identity constraint PK_BPAScheduleLog primary key, scheduleid int not null constraint FK_BPAScheduleLog_BPASchedule foreign key references BPASchedule (id) on delete cascade, instancetime datetime not null, firereason tinyint not null constraint CHK_BPAScheduleLog_firereason check (firereason < 5) ); create table BPAScheduleLogEntry ( id bigint not null identity constraint PK_BPAScheduleLogEntry primary key, schedulelogid int not null constraint FK_BPAScheduleLogEntry_BPAScheduleLog foreign key references BPAScheduleLog(id) on delete cascade, entrytype tinyint not null constraint CHK_BPAScheduleLogEntry_entrytype check (entrytype < 10), entrytime datetime not null, taskid int null constraint FK_BPAScheduleLogEntry_BPATask foreign key references BPATask(id) on delete no action, logsessionnumber int null constraint FK_BPAScheduleLogEntry_BPASession foreign key references BPASession(sessionnumber) ); create table BPAScheduleList ( id int not null identity constraint PK_BPAScheduleList primary key, listtype tinyint not null constraint CHK_BPAScheduleList_listtype check (listtype > 0 and listtype < 3), name varchar(64) not null, description text not null, relativedate tinyint not null constraint CHK_BPAScheduleList_relativedate check (relativedate < 4), absolutedate datetime null, daysdistance int not null, constraint UNQ_BPAScheduleList_listtype_name unique (listtype, name) ); create table BPAScheduleListSchedule ( schedulelistid int not null constraint FK_BPAScheduleListSchedule_BPAScheduleList foreign key references BPAScheduleList(id) on delete cascade, scheduleid int not null constraint FK_BPAScheduleListSchedule_BPASchedule foreign key references BPASchedule(id) on delete cascade, constraint PK_BPAScheduleListSchedule primary key (schedulelistid, scheduleid) ); insert into BPAScheduleList (listtype, name, description, relativedate, absolutedate, daysdistance) select 1, ''Yesterday''''s Reports'', ''Reports for all schedules which ran yesterday and today'', 2, NULL, 0 union all select 2, ''Today & Tomorrow'', ''Timetable for all schedules running today and tomorrow'', 1, NULL, 1; INSERT INTO BPADBVersion VALUES ( ''90'', GETUTCDATE(), ''db_upgradeR90.sql UTC'', ''Creation of all the public holiday, calendar, scheduler & related tables and any initial data'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='91') begin exec('alter table bpasysconfig add showusernamesonlogin Bit default 0 ')exec('')exec('update bpasysconfig set showusernamesonlogin = ''0'' ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''91'', GETUTCDATE(), ''db_upgradeR91.sql UTC'', ''Database amendments - Add column to BPASysConfig for configuring showing user names on login'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='92') begin exec('DECLARE @sver nvarchar(128) declare @ver int SET @sver = CAST(serverproperty(''ProductVersion'') AS nvarchar) SET @ver = convert(int, SUBSTRING(@sver, 1, CHARINDEX(''.'', @sver) - 1)) alter table BPACalendar drop constraint FK_BPACalendar_BPAPublicHolidayGroup; if (@ver > 8) exec(''alter table BPACalendar add constraint FK_BPACalendar_BPAPublicHolidayGroup foreign key (publicholidaygroupid) references BPAPublicHolidayGroup(id) on delete set null;'') alter table BPAPublicHolidayWorkingDay drop constraint FK_BPAPublicHolidayWorkingDay_BPAPublicHoliday; alter table BPAPublicHolidayWorkingDay add constraint FK_BPAPublicHolidayWorkingDay_BPAPublicHoliday foreign key (publicholidayid) references BPAPublicHoliday(id) on delete cascade; alter table BPANonWorkingDay drop constraint FK_BPANonWorkingDay_BPACalendar; alter table BPANonWorkingDay add constraint FK_BPANonWorkingDay_BPACalendar foreign key (calendarid) references BPACalendar(id) on delete cascade; alter table BPAPublicHolidayWorkingDay drop constraint FK_BPAPublicHolidayWorkingDay_BPACalendar; alter table BPAPublicHolidayWorkingDay add constraint FK_BPAPublicHolidayWorkingDay_BPACalendar foreign key (calendarid) references BPACalendar(id) on delete cascade; alter table BPAScheduleLogEntry drop constraint FK_BPAScheduleLogEntry_BPASession; if (@ver > 8) exec(''alter table BPAScheduleLogEntry add constraint FK_BPAScheduleLogEntry_BPASession foreign key (logsessionnumber) references BPASession(sessionnumber) on delete set null;'') INSERT INTO BPADBVersion VALUES ( ''92'', GETUTCDATE(), ''db_upgradeR92.sql UTC'', ''Foreign key refinements for the scheduler tables'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='93') begin exec('exec sp_RENAME ''BPATaskProcess'', ''BPATaskSession'' alter table BPATaskSession drop constraint PK_BPATaskProcess; alter table BPATaskSession add id int not null identity constraint PK_BPATaskSession primary key; INSERT INTO BPADBVersion VALUES ( ''93'', GETUTCDATE(), ''db_upgradeR93.sql UTC'', ''Renamed BPATaskProcess to BPATaskSession, and allowed the same '' + ''process to run on the same resource within the same scheduler task'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='94') begin exec('alter table BPASchedule add versionno int null; ')exec('')exec('update BPASchedule set versionno=1; alter table BPASchedule alter column versionno int not null; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''94'', GETUTCDATE(), ''db_upgradeR94.sql UTC'', ''Added a version number field to the scheduler'' + ''process to run on the same resource within the same scheduler task'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='95') begin exec('UPDATE BPAStatus set description=''Terminated'' where description=''Exception''; INSERT INTO BPADBVersion VALUES ( ''95'', GETUTCDATE(), ''db_upgradeR95.sql UTC'', ''Change session status description from Exception to Terminated. See also script 74'' ) ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='96') begin exec('alter table BPAScheduleLogEntry add terminationreason varchar(255) null, stacktrace text null; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''96'', GETUTCDATE(), ''db_upgradeR96.sql UTC'', ''Add termination reason and stack trace to schedule log entries'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='97') begin exec('alter table BPAUser add systemusername varchar(128) null; ')exec('')exec('insert into BPAUser (userid, systemusername) values (newid(), ''Scheduler''); INSERT INTO BPADBVersion VALUES ( ''97'', GETUTCDATE(), ''db_upgradeR97.sql UTC'', ''Created system user using a ''''systemusername'''' field on BPAUser'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='98') begin exec('create table BPADataTracker ( dataname varchar(64) not null constraint PK_BPADataTracker primary key, versionno bigint not null ); ')exec('')exec('insert into BPADataTracker (dataname, versionno) values (''Scheduler'', 1); INSERT INTO BPADBVersion VALUES ( ''98'', GETUTCDATE(), ''db_upgradeR98.sql UTC'', ''Created the BPADataTracker table to hold simplistic version numbers for arbitrary data'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='99') begin exec('alter table BPAScheduleTrigger add usertrigger bit not null constraint DEF_BPAScheduleTrigger_usertrigger default 1; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''99'', GETUTCDATE(), ''db_upgradeR99.sql UTC'', ''Added a flag to indicate if a trigger can be configured using the UI or not.'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='100') begin exec('update BPAScheduleList set name=''Recent Activity'' where listtype = 1 and name = ''Yesterday''''s Reports''; ')exec('')exec('if not exists (select id from BPASchedule where name=''Schedule 1'' union all select id from BPATask where name=''Task 1'') begin declare @scheduleid int; insert into BPASchedule (name, description, initialtaskid, retired, versionno) values (''New Schedule'', '''', NULL, 0, 1); set @scheduleid = scope_identity(); insert into BPATask (scheduleid, name, description) values (@scheduleid, ''New Schedule - New Task'', ''''); update BPASchedule set initialtaskid=scope_identity() where id = @scheduleid; end ')exec('')exec('alter table BPATask drop constraint UNQ_BPATask_name; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''100'', GETUTCDATE(), ''db_upgradeR100.sql UTC'', ''Added an example schedule and task; Renamed the example timetable; Removed standalone UNIQUE constraint on BPATask.name'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='101') begin exec('update BPAScheduleTrigger set period = 1, unittype = 2 where unittype = 3 and calendarid is not null; alter table BPASchedule alter column name varchar(128) not null; alter table BPATask alter column name varchar(128) not null; alter table BPACalendar alter column name varchar(128) not null; alter table BPAScheduleList alter column name varchar(128) not null; alter table BPAScheduleList add allschedules bit not null constraint DEF_BPAScheduleList_allschedules default 0; ')exec('')exec('update l set l.allschedules = 1 from BPAScheduleList l left join BPAScheduleListSchedule s on l.id = s.schedulelistid where s.schedulelistid is null; INSERT INTO BPADBVersion VALUES ( ''101'', GETUTCDATE(), ''db_upgradeR101.sql UTC'', ''Moved predefined weekly triggers with calendar to daily; Increased max name lengths'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='102') begin exec('update BPAScheduleList set relativedate = 1, daysdistance = 2, allschedules = 1, absolutedate = NULL where (listtype = 1 and name = ''Recent Activity'') or (listtype = 2 and name = ''Today & Tomorrow''); INSERT INTO BPADBVersion VALUES ( ''102'', GETUTCDATE(), ''db_upgradeR102.sql UTC'', ''Change the default report & timetable to show more useful data'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='103') begin exec('INSERT INTO BPAPermission (PermissionID,[Name]) VALUES (17179869184,''View Schedule'') INSERT INTO BPAPermission (PermissionID,[Name]) VALUES (34359738368,''Edit Schedule'') INSERT INTO BPAPermission (PermissionID,[Name]) VALUES (68719476736,''Create Schedule'') INSERT INTO BPAPermission (PermissionID,[Name]) VALUES (137438953472,''Delete Schedule'') INSERT INTO BPAPermission (PermissionID,[Name]) VALUES (257698037760,''Scheduler'') DECLARE @NextRole as int set @NextRole = 2 * (SELECT MAX(RoleID) FROM BPARole) INSERT INTO BPARole (RoleID, RoleName, RolePermissions,SingleSignonUserGroup) VALUES (@NextRole,''Schedule Manager'',257698037760,NULL) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''103'', GETUTCDATE(), ''db_upgradeR103.sql UTC'', ''Add Scheduler Permissions and Roles to DB'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='104') begin exec('ALTER TABLE BPAUser ADD loginattempts int NOT NULL CONSTRAINT DEF_BPAUser_loginattempt DEFAULT 0 ALTER TABLE BPASysConfig ADD maxloginattempts int NULL ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''104'', GETUTCDATE(), ''db_upgradeR104.sql UTC'', ''Add Maximum login attempts'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='105') begin exec('delete BPAAlertEvent from BPAAlertEvent e left join BPAProcess p on e.ProcessID = p.processid left join BPAResource r on e.ResourceID = r.resourceid where p.processid is null or r.resourceid is null; alter table BPAAlertEvent add scheduleid int null constraint FK_BPAAlertEvent_BPASchedule foreign key references BPASchedule(id) on delete cascade, taskid int null constraint FK_BPAAlertEvent_BPATask foreign key references BPATask(id), constraint FK_BPAAlertEvent_BPAProcess foreign key (processid) references BPAProcess(processid) on delete cascade, constraint FK_BPAAlertEvent_BPAResource foreign key (resourceid) references BPAResource(resourceid) on delete cascade; update BPAUser set alerteventtypes = 0 where alerteventtypes is null; update BPAUser set alertnotificationtypes = 0 where alertnotificationtypes is null; update BPAAlertEvent set AlertEventType = 0 where AlertEventType is null; update BPAAlertEvent set AlertNotificationType = 0 where AlertNotificationType is null; alter table BPAUser alter column alerteventtypes int not null; alter table BPAUser alter column alertnotificationtypes int not null; alter table BPAUser add constraint DEF_BPAUser_alerteventtypes default 0 for alerteventtypes, constraint DEF_BPAUser_alertnotificationtypes default 0 for alertnotificationtypes; alter table BPAAlertEvent alter column AlertEventType int not null; alter table BPAAlertEvent alter column AlertNotificationType int not null; exec sp_rename ''BPAAlert'', ''BPAProcessAlert'' create table BPAScheduleAlert ( userid uniqueidentifier not null constraint FK_BPAScheduleAlert_BPAUser foreign key references BPAUser(userid) on delete cascade, scheduleid int not null constraint FK_BPAScheduleAlert_BPASchedule foreign key references BPASchedule(id) on delete cascade, constraint PK_BPAScheduleAlert primary key (userid, scheduleid) ); INSERT INTO BPADBVersion VALUES ( ''105'', GETUTCDATE(), ''db_upgradeR105.sql UTC'', ''Add schedule and task IDs to the alert event; '' + ''Ensure alert events are deleted if the process/resource they refer to is deleted; '' + ''Make the alert types on user more useful defaults'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='106') begin exec('CREATE TABLE BPAPasswordRules ( id int NOT NUll default 1 constraint PK_BPAPasswordRules primary key, uppercase bit NOT NULL, lowercase bit NOT NULL, digits bit NOT NULL, special bit NOT NULL, brackets bit NOT NULL, length int NOT NULL, additional varchar(128) NOT NULL ) ')exec('')exec('INSERT INTO BPAPasswordRules VALUES ( 1, 0, 0, 0, 0, 0, 0, '''' ) INSERT INTO BPADBVersion VALUES ( ''106'', GETUTCDATE(), ''db_upgradeR106.sql UTC'', ''Adds password rules table'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='107') begin exec('INSERT INTO BPAPermission (PermissionID,Name) VALUES (274877906944,''Retire Schedule'') UPDATE BPAPermission SET PermissionID=532575944704 WHERE PermissionID=257698037760 UPDATE BPARole Set RolePermissions=532575944704 WHERE RoleID=128 INSERT INTO BPADBVersion VALUES ( ''107'', GETUTCDATE(), ''db_upgradeR107.sql UTC'', ''Adds permission to retire schedules'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='108') begin exec('ALTER TABLE BPASchedule ALTER COLUMN name varchar(128) NULL ALTER TABLE BPASchedule ADD deletedname varchar(128) NULL ALTER TABLE BPATask ALTER COLUMN name varchar(128) NULL INSERT INTO BPADBVersion VALUES ( ''108'', GETUTCDATE(), ''db_upgradeR108.sql UTC'', ''Makes BPASchedule entries hideable, and also makes BPATask names nullable'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='109') begin exec('alter table BPASchedule drop constraint UNQ_BPASchedule_name; alter table BPATask drop constraint UNQ_BPATask_scheduleid_name; INSERT INTO BPADBVersion VALUES ( ''109'', GETUTCDATE(), ''db_upgradeR109.sql UTC'', ''Removed UNIQUE constraint from BPASchedule.name and BPATask.name'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='110') begin exec('alter table BPAScheduleTrigger drop constraint CHK_BPAScheduleTrigger; alter table BPAScheduleTrigger add constraint CHK_BPAScheduleTrigger check (unittype < 8); INSERT INTO BPADBVersion VALUES ( ''110'', GETUTCDATE(), ''db_upgradeR110.sql UTC'', ''Increases the allowed range of the schedule interval type to allow for minutes and seconds'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='111') begin exec('create view BPViewWorkQueueItemTag (queueitemident, tag) as select it.queueitemident, t.tag from BPAWorkQueueItemTag it join BPATag t on it.tagid = t.id union select i.ident, ''Exception: '' + REPLACE(cast(i.exceptionreason as varchar(1000)),'';'','':'') from BPAWorkQueueItem i where i.exceptionreason is not null ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''111'', GETUTCDATE(), ''db_upgradeR111.sql UTC'', ''Supports virtual tags by creating a view which takes them into account'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='112') begin exec('alter table BPATag alter column tag varchar(255) not null ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''112'', GETUTCDATE(), ''db_upgradeR112.sql UTC'', ''Increased the permitted length of work queue item tags'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='113') begin exec('DECLARE @sver nvarchar(128) declare @ver int SET @sver = CAST(serverproperty(''ProductVersion'') AS nvarchar) SET @ver = convert(int, SUBSTRING(@sver, 1, CHARINDEX(''.'', @sver) - 1)) if @ver > 8 exec('' alter table BPAWorkQueueItem add lastupdated as case when exception > completed then exception when exception < completed then completed else loaded end persisted ,queuepositiondate as case when exception is null and completed is null and locked is null and (deferred is null or deferred < GetUTCDate()) then loaded else cast(''''99991231'''' as datetime) end ,exceptionreasonvarchar as cast(exceptionreason as varchar(1024)) ,prevworktime int not null default 0 ,attemptworktime as worktime - prevworktime persisted ,state as case when exception is not null then 5 when completed is not null then 4 when deferred is not null then 3 when locked is not null then 2 else 1 end persisted ,finished as isnull(exception,completed) persisted'') else exec('' alter table BPAWorkQueueItem add lastupdated as case when exception > completed then exception when exception < completed then completed else loaded end ,queuepositiondate as case when exception is null and completed is null and locked is null and (deferred is null or deferred < GetUTCDate()) then loaded else cast(''''99991231'''' as datetime) end ,exceptionreasonvarchar as cast(exceptionreason as varchar(1024)) ,prevworktime int not null default 0 ,attemptworktime as worktime - prevworktime ,state as case when exception is not null then 5 when completed is not null then 4 when deferred is not null then 3 when locked is not null then 2 else 1 end ,finished as isnull(exception,completed)'') ')exec('')exec('update i set i.prevworktime = isnull(iprev.worktime,0) from BPAWorkQueueItem i left join BPAWorkQueueItem iprev on i.id = iprev.id and i.attempt = iprev.attempt+1; INSERT INTO BPADBVersion VALUES ( ''113'', GETUTCDATE(), ''db_upgradeR113.sql UTC'', ''Add commonly used / useful (largely calculated) columns to work queue items'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='114') begin exec('alter table BPAWorkQueueItem drop column exceptionreasonvarchar; ')exec('')exec('alter table BPAWorkQueueItem add exceptionreasonvarchar as cast(exceptionreason as varchar(500)) ')exec('')exec('DECLARE @sver nvarchar(128) declare @ver int SET @sver = CAST(serverproperty(''ProductVersion'') AS nvarchar) SET @ver = convert(int, SUBSTRING(@sver, 1, CHARINDEX(''.'', @sver) - 1)) if @ver > 8 begin create index INDEX_BPAWorkQueueItem_lastupdated on BPAWorkQueueItem(lastupdated) create index INDEX_BPAWorkQueueItem_finished on BPAWorkQueueItem(finished) create index INDEX_BPAWorkQueueItem_exceptionreasonvarchar on BPAWorkQueueItem(exceptionreasonvarchar) end ')exec('')exec('alter view BPViewWorkQueueItemTag (queueitemident, tag) as select it.queueitemident, t.tag from BPAWorkQueueItemTag it join BPATag t on it.tagid = t.id union select i.ident, ''Exception: '' + REPLACE(i.exceptionreasonvarchar,'';'','':'') from BPAWorkQueueItem i where i.exceptionreasonvarchar is not null ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''114'', GETUTCDATE(), ''db_upgradeR114.sql UTC'', ''Added indexes to BPAWorkQueueItem for calculated columns'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='115') begin exec('DELETE FROM BPARole WHERE RoleID = 2 DELETE FROM BPARole WHERE RoleName = ''Business Object Designer'' DELETE FROM BPARole WHERE RoleID = 16 DECLARE @NextRole as int set @NextRole = 2 * (SELECT MAX(RoleID) FROM BPARole) INSERT INTO BPARole (RoleID, RoleName, RolePermissions) VALUES (@NextRole, ''Designer'', 267911295) set @NextRole = 2 * (SELECT MAX(RoleID) FROM BPARole) INSERT INTO BPARole (RoleID, RoleName, RolePermissions) VALUES (@NextRole, ''Tester'', 8594587712) UPDATE BPARole SET RoleName = ''Process Administrator'' WHERE RoleID = 8 ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''115'', GETUTCDATE(), ''db_upgradeR115.sql UTC'', ''Ammended Default Roles to match delivery methodology'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='116') begin exec('UPDATE BPAPermission SET Name = ''Processes - Management'' WHERE Name = ''Process Management'' INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x8000000000,''Processes - Grouping'') INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x10000000000,''Processes - History'') INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x20000000000,''Processes - Exception Types'') UPDATE BPAPermission SET Name = ''Business Objects - Management'' WHERE Name = ''Business Object Management'' INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x40000000000,''Business Objects - History'') INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x80000000000,''Business Objects - External'') INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x100000000000,''Business Objects - Exception Types'') UPDATE BPAPermission SET Name = ''Business Objects - Web Services'' WHERE Name = ''Web Service Management'' UPDATE BPAPermission SET Name = ''Resources - Management'' WHERE Name = ''Resource Management'' INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x200000000000,''Resources - Pools'') INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x400000000000,''Workflow - Work Queue Configuration'') UPDATE BPAPermission SET Name = ''Audit - Audit Logs'' WHERE Name = ''System Manager Logs'' INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x800000000000,''Audit - Process Logs'') INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x1000000000000,''Audit - Business Object Logs'') INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x2000000000000,''Audit - Statistics'') UPDATE BPAPermission SET Name = ''Security - Users'' WHERE Name = ''User Management'' INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x4000000000000,''Security - Credentials'') INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x8000000000000,''Security - Password Options'') UPDATE BPAPermission SET Name = ''System - Settings'' WHERE Name = ''General Settings'' INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x10000000000000,''System - License'') UPDATE BPAPermission SET Name = ''System - Archiving'' WHERE Name = ''Database Management'' INSERT INTO BPAPermission (PermissionID,Name) VALUES (0x20000000000000,''System - Calendars'') declare @tot bigint; set @tot = ( select sum(PermissionID) from BPAPermission where Name in ( ''Processes - Management'', ''Processes - Grouping'', ''Processes - History'', ''Processes - Exception Types'', ''Business Objects - Management'', ''Business Objects - History'', ''Business Objects - External'', ''Business Objects - Exception Types'', ''Business Objects - Web Services'', ''Resources - Management'', ''Resources - Pools'', ''Workflow - Work Queue Configuration'', ''Audit - Audit Logs'', ''Audit - Process Logs'', ''Audit - Business Object Logs'', ''Audit - Statistics'', ''Security - Users'', ''Security - Credentials'', ''Security - Password Options'', ''System - License'', ''System - Calendars'', ''System - Archiving'', ''System - Settings'' ) ) UPDATE BPAPermission SET PermissionID = @tot WHERE Name = ''System Manager'' ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''116'', GETUTCDATE(), ''db_upgradeR116.sql UTC'', ''Ammended permission names to better reflect system manager areas.'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='117') begin exec('alter table BPAWorkQueueItem alter column status varchar(255) null; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''117'', GETUTCDATE(), ''db_upgradeR117.sql UTC'', ''Extend WorkQueueItem.status to 255 chars.'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='118') begin exec('UPDATE BPARole SET RoleName = ''Developer'' WHERE RoleName = ''Designer'' DELETE FROM BPAPermission WHERE PermissionID = 8192 DELETE FROM BPAPermission WHERE PermissionID = 16384 DELETE FROM BPAPermission WHERE PermissionID = 32768 DELETE FROM BPAPermission WHERE PermissionID = 57344 DELETE FROM BPAPermission WHERE Name = ''Report Management'' INSERT INTO BPADBVersion VALUES ( ''118'', GETUTCDATE(), ''db_upgradeR118.sql UTC'', ''Update Role from Designer to Developer and remove Report Console Permission'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='119') begin exec('create table BPAWorkQueueLog ( logid bigint identity not null primary key nonclustered, eventtime datetime not null, queueident int not null, queueop tinyint not null, itemid uniqueidentifier null, keyvalue varchar(255) not null ); ')exec('')exec('create clustered index INDEX_BPAWorkQueueLog_eventtime on BPAWorkQueueLog(eventtime); create index INDEX_BPAWorkQueueLog_queueident on BPAWorkQueueLog(queueident); create index INDEX_BPAWorkQueueLog_queueop on BPAWorkQueueLog(queueop); INSERT INTO BPADBVersion VALUES ( ''119'', GETUTCDATE(), ''db_upgradeR119.sql UTC'', ''Add Queue auditing for the new pricing model'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='120') begin exec('update BPARole set rolepermissions = rolepermissions | ( select sum(permissionid) from BPAPermission where name in (''Audit - Process Logs'', ''Audit - Business Object Logs'') ) where rolename = ''Process Administrator''; INSERT INTO BPADBVersion VALUES ( ''120'', GETUTCDATE(), ''db_upgradeR120.sql UTC'', ''Update Process Administrator role to allow viewing of logs'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='121') begin exec('alter table BPATaskSession add resourcename varchar(128) null; ')exec('')exec('update s set s.resourcename = r.name from BPATaskSession s join BPAResource r on s.resourceid = r.resourceid; alter table BPATaskSession alter column resourcename varchar(128) not null; alter table BPATaskSession drop constraint FK_BPATaskProcess_BPAResource; ')exec('')exec('alter table BPATaskSession drop column resourceid; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''121'', GETUTCDATE(), ''db_upgradeR121.sql UTC'', ''Makes Scheduler use name to identify a resource rather than ID'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='122') begin exec('alter table BPAWorkQueueItem drop column state; ')exec('')exec('alter table BPAWorkQueueItem add state as ( case when exception is not null then 5 when completed is not null then 4 when (deferred is not null and deferred > getutcdate()) then 3 when locked is not null then 2 else 1 end); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''122'', GETUTCDATE(), ''db_upgradeR122.sql UTC'', ''Fixes BPAWorkQueueItem.state to correctly represent deferred / pending states'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='123') begin exec('create table BPAPref ( id int identity not null primary key, name varchar(255) not null, userid uniqueidentifier null constraint FK_BPAPref_BPAUser foreign key references BPAUser(userid) on delete cascade, constraint UNQ_BPAPref_name_userid unique (name, userid) ); create table BPAIntegerPref ( prefid int not null constraint FK_BPAIntegerPref_BPAPref foreign key references BPAPref(id) on delete cascade, value int not null ); create table BPAStringPref ( prefid int not null constraint FK_BPAStringPref_BPAPref foreign key references BPAPref(id) on delete cascade, value text not null ); INSERT INTO BPADBVersion VALUES ( ''123'', GETUTCDATE(), ''db_upgradeR123.sql UTC'', ''Introduces a basic preferences system'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='124') begin exec('declare @newpermid bigint; set @newpermid = (select 2 * max(PermissionID) from BPAPermission); insert into BPAPermission (PermissionID, Name) values (@newpermid, ''System - Scheduler''); update BPAPermission set PermissionID = (PermissionID | @newpermid) where Name = ''System Manager''; update BPARole set RolePermissions = (RolePermissions | @newpermid) where RoleName in (''Schedule Manager'',''System Administrator''); INSERT INTO BPADBVersion VALUES ( ''124'', GETUTCDATE(), ''db_upgradeR124.sql UTC'', ''Adds a permission for configuring the scheduler'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='125') begin exec('update BPAPermission set PermissionID = cast(0x40000000000000 as bigint) where name = ''System - Scheduler''; declare @sysman bigint, @schedman bigint; set @sysman = ( select sum(PermissionID) from BPAPermission where Name in ( ''Processes - Management'', ''Processes - Grouping'', ''Processes - History'', ''Processes - Exception Types'', ''Business Objects - Management'', ''Business Objects - History'', ''Business Objects - External'', ''Business Objects - Exception Types'', ''Business Objects - Web Services'', ''Resources - Management'', ''Resources - Pools'', ''Workflow - Work Queue Configuration'', ''Audit - Audit Logs'', ''Audit - Process Logs'', ''Audit - Business Object Logs'', ''Audit - Statistics'', ''Security - Users'', ''Security - Credentials'', ''Security - Password Options'', ''System - License'', ''System - Calendars'', ''System - Archiving'', ''System - Settings'', ''System - Scheduler'' ) ); set @schedman = ( select sum(PermissionID) from BPAPermission where Name in ( ''Retire Schedule'', ''Delete Schedule'', ''Create Schedule'', ''Edit Schedule'', ''View Schedule'', ''System - Scheduler'' ) ); update BPAPermission set PermissionID = @sysman where Name = ''System Manager''; update BPAPermission set PermissionID = @schedman where Name = ''Scheduler''; INSERT INTO BPADBVersion VALUES ( ''125'', GETUTCDATE(), ''db_upgradeR125.sql UTC'', ''Fixes permission errors introduced in 124'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='126') begin exec('create unique index UNQ_BPATag_tag on BPATag(tag) ')exec('')exec('alter table BPAWorkQueueItemTag drop constraint PK_BPAWorkQueueItemTag; ')exec('')exec('create unique clustered index PK_BPAWorkQueueItemTag on BPAWorkQueueItemTag (queueitemident,tagid) with (ignore_dup_key = on); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''126'', GETUTCDATE(), ''db_upgradeR126.sql UTC'', ''Some support for increasing performance in tags'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='127') begin exec('create table BPAEnvLock ( name varchar(255) not null constraint PK_BPAEnvLock primary key, token varchar(255) null, sessionid uniqueidentifier null constraint FK_BPAEnvLock_BPASession foreign key references BPASession(sessionid), locktime datetime null, comments varchar(1024) null ); create index IX_BPAEnvLock_token on BPAEnvLock(token); INSERT INTO BPADBVersion VALUES ( ''127'', GETUTCDATE(), ''db_upgradeR127.sql UTC'', ''Support for the environment locking business object'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='128') begin exec('create view BPVSessionInfo as select s.sessionid as "sessionid", s.sessionnumber as "sessionnumber", s.startdatetime as "startdatetime", s.enddatetime as "enddatetime", s.processid as "processid", p.name as "processname", s.starterresourceid as "starterresourceid", sr.name as "starterresourcename", s.starteruserid as "starteruserid", isnull(su.username, ''['' + su.systemusername + '']'') as "starterusername", s.runningresourceid as "runningresourceid", rr.name as "runningresourcename", s.runningosusername as "runningosusername", s.statusid as "statusid", s.startparamsxml as "startparamsxml", s.logginglevelsxml as "logginglevelsxml", s.sessionstatexml as "sessionstatexml" from BPASession s join BPAProcess p on s.processid = p.processid join BPAResource sr on s.starterresourceid = sr.resourceid join BPAResource rr on s.runningresourceid = rr.resourceid join BPAUser su on s.starteruserid = su.userid ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''128'', GETUTCDATE(), ''db_upgradeR128.sql UTC'', ''Adds the BPVSessionInfo view, combining user, resource and process data into a single view'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='129') begin exec('declare @perm bigint set @perm = cast(0x80000000000000 as bigint) insert into BPAPermission (PermissionID, name) values (@perm, ''Workflow - Environment Locking'') update BPAPermission set PermissionID = PermissionID | @perm where name = ''System Manager'' update BPARole set RolePermissions = RolePermissions | @perm where RoleName = ''System Administrator'' INSERT INTO BPADBVersion VALUES ( ''129'', GETUTCDATE(), ''db_upgradeR129.sql UTC'', ''Adds permissions for the locking UI, adds Scheduler permission to SysAdmin'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='130') begin exec('declare @sver nvarchar(128) declare @ver int set @sver = cast(serverproperty(''ProductVersion'') AS nvarchar) set @ver = convert(int, SUBSTRING(@sver, 1, CHARINDEX(''.'', @sver) - 1)) if @ver > 8 drop index INDEX_BPAWorkQueueItem_lastupdated on BPAWorkQueueItem alter table BPAWorkQueueItem drop column lastupdated; if @ver > 8 exec('' alter table BPAWorkQueueItem add lastupdated as coalesce(completed,exception,locked,loaded) persisted'') else exec('' alter table BPAWorkQueueItem add lastupdated as coalesce(completed,exception,locked,loaded)'') if @ver > 8 create index INDEX_BPAWorkQueueItem_lastupdated on BPAWorkQueueItem(lastupdated) alter table BPAWorkQueue alter column name varchar(255) not null; alter table BPAWorkQueue alter column keyfield varchar(255) not null; drop index Index_BPAWorkQueueItem_key on BPAWorkQueueItem; alter table BPAWorkQueueItem alter column keyvalue varchar(255) not null; create index Index_BPAWorkQueueItem_key on BPAWorkQueueItem(keyvalue); INSERT INTO BPADBVersion VALUES ( ''130'', GETUTCDATE(), ''db_upgradeR130.sql UTC'', ''Fixes queueitem.lastupdated column; Increases some field lengths'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='131') begin exec('alter table bpasessionlog add automateworkingset bigint default 0 alter table bpasessionlog add targetappname varchar(32) default NULL alter table bpasessionlog add targetappworkingset bigint default 0 INSERT INTO BPADBVersion VALUES ( ''131'', GETUTCDATE(), ''db_upgradeR131.sql UTC'', ''Adds session log fields for storage of diagnostics information'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='132') begin exec('alter table bparesource add diagnostics int default 0 not NULL INSERT INTO BPADBVersion VALUES ( ''132'', GETUTCDATE(), ''db_upgradeR132.sql UTC'', ''Add Resource PC diagnostics configuration'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='133') begin exec('CREATE TABLE BPAEnvironmentVar ( name varchar(64) NOT NULL, datatype varchar(16) NOT NULL, value text NOT NULL, description text NOT NULL, CONSTRAINT PK_BPAEnvironmentVar PRIMARY KEY CLUSTERED ( name ) ) CREATE TABLE BPAProcessEnvVar ( processid uniqueidentifier NOT NULL, name varchar(64) NOT NULL, CONSTRAINT PK_BPAProcessEnvVar PRIMARY KEY CLUSTERED ( processid,name ), CONSTRAINT FK_BPAProcessEnvVar_BPAProcess FOREIGN KEY ( processid ) REFERENCES BPAProcess ( processid ) ) INSERT INTO BPADBVersion VALUES ( ''133'', GETUTCDATE(), ''db_upgradeR133.sql UTC'', ''Add tables for environment variables'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='134') begin exec('DECLARE @NewIndex BIGINT SET @NewIndex= 1 DECLARE @Count BIGINT SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission (Name,PermissionID) VALUES (''Modify Environment Variables'', @NewIndex) UPDATE BPAUser SET Permissions = Permissions & (~@NewIndex) UPDATE BPAPermission set PermissionID = PermissionID | @NewIndex WHERE Name=''System Manager'' UPDATE BPARole set RolePermissions = RolePermissions | @NewIndex WHERE RoleName=''System Administrator'' INSERT INTO BPADBVersion VALUES ( ''134'', GETUTCDATE(), ''db_upgradeR134.sql UTC'', ''New permission for Environment Variables'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='135') begin exec('IF object_id(''PK_BPAWebService'') IS NULL alter table BPAWebService add constraint PK_BPAWebService primary key (serviceid) create table BPAPackage ( id int not null identity constraint PK_BPAPackage primary key, name varchar(255) not null constraint UNQ_BPAPackage_name unique, description text not null, userid uniqueidentifier not null, created datetime not null ) create table BPAPackageProcess ( packageid int not null constraint FK_BPAPackageProcess_BPAPackage foreign key references BPAPackage(id) on delete cascade, processid uniqueidentifier not null constraint FK_BPAPackageProcess_BPAProcess foreign key references BPAProcess(processid) on delete cascade, constraint PK_BPAPackageProcess primary key (packageid, processid) ) create table BPAPackageProcessGroupMember ( packageid int not null constraint FK_BPAPackageProcessGroup_BPAPackage foreign key references BPAPackage(id) on delete cascade, processgroupid uniqueidentifier not null, processid uniqueidentifier not null, constraint FK_BPAPackageProcessGroup_BPAProcessGroupMembership foreign key (processgroupid, processid) references BPAProcessGroupMembership(GroupID,ProcessID) on delete cascade, constraint FK_BPAPackageProcessGroupMember_BPAPackageProcess foreign key (packageid, processid) references BPAPackageProcess(packageid,processid), constraint PK_BPAPackageProcessGroup primary key (packageid, processgroupid, processid) ) create table BPAPackageWorkQueue ( packageid int not null constraint FK_BPAPackageWorkQueue_BPAPackage foreign key references BPAPackage(id) on delete cascade, queueident int not null constraint FK_BPAPackageWorkQueue_BPAWorkQueue foreign key references BPAWorkQueue(ident) on delete cascade, constraint PK_BPAPackageWorkQueue primary key (packageid, queueident) ) create table BPAPackageCredential ( packageid int not null constraint FK_BPAPackageCredential_BPAPackage foreign key references BPAPackage(id) on delete cascade, credentialid uniqueidentifier not null constraint FK_BPAPackageCredential_BPACredentials foreign key references BPACredentials(id) on delete cascade, constraint PK_BPAPackageCredential primary key (packageid, credentialid) ) create table BPAPackageSchedule ( packageid int not null constraint FK_BPAPackageSchedule_BPAPackage foreign key references BPAPackage(id) on delete cascade, scheduleid int not null constraint FK_BPAPackageSchedule_BPASchedule foreign key references BPASchedule(id) on delete cascade, constraint PK_BPAPackageSchedule primary key (packageid, scheduleid) ) create table BPAPackageScheduleList ( packageid int not null constraint FK_BPAPackageScheduleList_BPAPackage foreign key references BPAPackage(id) on delete cascade, schedulelistid int not null constraint FK_BPAPackageScheduleList_BPAScheduleList foreign key references BPAScheduleList(id) on delete cascade, constraint PK_BPAPackageScheduleList primary key (packageid, schedulelistid) ) create table BPAPackageWebService ( packageid int not null constraint FK_BPAPackageWebService_BPAPackage foreign key references BPAPackage(id) on delete cascade, webserviceid uniqueidentifier not null constraint FK_BPAPackageWebService_BPAWebService foreign key references BPAWebService(serviceid) on delete cascade, constraint PK_BPAPackageWebService primary key (packageid, webserviceid) ) create table BPAPackageEnvironmentVar ( packageid int not null constraint FK_BPAPackageEnvironmentVar_BPAPackage foreign key references BPAPackage(id) on delete cascade, name varchar(64) not null constraint FK_BPAPackageEnvironmentVar_BPAEnvironmentVar foreign key references BPAEnvironmentVar(name) on delete cascade on update cascade, constraint PK_BPAPackageEnvironmentVar primary key (packageid, name) ) create table BPARelease ( id int not null identity constraint PK_BPARelease primary key, packageid int not null constraint FK_BPARelease_BPAPackage foreign key references BPAPackage(id) on delete cascade, name varchar(255) not null, created datetime not null, userid uniqueidentifier not null constraint FK_BPARelease_BPAUser foreign key references BPAUser(userid), notes text not null, compressedxml image null, constraint UNQ_BPARelease_packageid_name unique (packageid, name) ) create table BPAReleaseEntry ( id int not null identity constraint PK_BPAReleaseEntry primary key, releaseid int not null constraint FK_BPAReleaseEntry_BPARelease foreign key references BPARelease(id) on delete cascade, typekey varchar(64) not null, entityid varchar(255) not null, name varchar(255) not null ) INSERT INTO BPADBVersion VALUES ( ''135'', GETUTCDATE(), ''db_upgradeR135.sql UTC'', ''Gives WebService a primary key - introduces packages and releases'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='136') begin exec('create table BPAFont ( name varchar(255) not null constraint PK_BPAFont primary key, version varchar(255) not null, fontdata text not null, ) INSERT INTO BPADBVersion VALUES ( ''136'', GETUTCDATE(), ''db_upgradeR136.sql UTC'', ''Add table for font storage'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='137') begin exec('IF OBJECT_ID(''chk'') IS NOT NULL DROP PROC chk ')exec('')exec('CREATE PROC chk @id int,@cat int,@typeid int,@msg nvarchar(255) AS insert into BPAValCheck (checkid,catid,typeid,description) values (@id,@cat,@typeid,@msg) ')exec('')exec('create table BPAValCategory ( catid int constraint PK_BPAValCategory primary key, description varchar(255) not null ) DECLARE @StageValidation int SET @StageValidation=0 DECLARE @FlowValidation int SET @FlowValidation=1 DECLARE @DocumentationControl int SET @DocumentationControl=2 insert into BPAValCategory (catid,description) values (@StageValidation,''Stage Validation'') insert into BPAValCategory (catid,description) values (@FlowValidation,''Flow Validation'') insert into BPAValCategory (catid,description) values (@DocumentationControl,''Documentation Control'') create table BPAValType ( typeid int constraint PK_BPAValType primary key, description varchar(255) not null ) DECLARE @Error int SET @Error=0 DECLARE @Warning int SET @Warning=1 DECLARE @Advice int SET @Advice=2 insert into BPAValType (typeid,description) values (@Error,''Error'') insert into BPAValType (typeid,description) values (@Warning,''Warning'') insert into BPAValType (typeid,description) values (@Advice,''Advice'') create table BPAValAction ( actionid int constraint PK_BPAValAction primary key, description varchar(255) not null ) insert into BPAValAction (actionid,description) values (0,''Ignore'') insert into BPAValAction (actionid,description) values (1,''Validate'') insert into BPAValAction (actionid,description) values (2,''Validate and Prevent Publication'') insert into BPAValAction (actionid,description) values (3,''Validate and Prevent Save'') create table BPAValActionMap ( catid int not null references BPAValCategory(catid), typeid int not null references BPAValType(typeid), actionid int not null references BPAValAction(actionid), constraint PK_BPAValActionMap primary key (catid, typeid, actionid) ) insert into BPAValActionMap (catid,typeid,actionid) values (0,0,1) insert into BPAValActionMap (catid,typeid,actionid) values (0,1,1) insert into BPAValActionMap (catid,typeid,actionid) values (0,2,1) insert into BPAValActionMap (catid,typeid,actionid) values (1,0,1) insert into BPAValActionMap (catid,typeid,actionid) values (1,1,1) insert into BPAValActionMap (catid,typeid,actionid) values (1,2,1) insert into BPAValActionMap (catid,typeid,actionid) values (2,0,1) insert into BPAValActionMap (catid,typeid,actionid) values (2,1,1) insert into BPAValActionMap (catid,typeid,actionid) values (2,2,0) create table BPAValCheck ( checkid int constraint PK_BPAValCheck primary key, catid int not null references BPAValCategory(catid), typeid int not null references BPAValType(typeid), description varchar(255) not null ) EXEC chk 0,@StageValidation,@Error,"Blank choice expression on {0}" EXEC chk 1,@StageValidation,@Error,"Invalid choice expression on {0}" EXEC chk 2,@StageValidation,@Error,"Expression does not result in a Flag value on {0}" EXEC chk 3,@StageValidation,@Warning,"No name assigned to {0}" EXEC chk 4,@FlowValidation,@Error,"No link from {0}" EXEC chk 5,@FlowValidation,@Error,"Invalid link from {0}" EXEC chk 6,@FlowValidation,@Error,"Link to a different page from {0}" EXEC chk 7,@StageValidation,@Error,"Cannot store data in an environment variable" EXEC chk 8,@StageValidation,@Error,"Can not determine resulting data type of expression{0}" EXEC chk 9,@StageValidation,@Error,"Expression does not evaluate to a compatible target data type{0}" EXEC chk 10,@StageValidation,@Error,"Field ''{0}'' does not exist in the collection{1}" EXEC chk 11,@StageValidation,@Error,"Stage to store result in is not accessible from this page{0}" EXEC chk 12,@StageValidation,@Error,"Stage to store in is not a Data or Collection stage{0}" EXEC chk 13,@StageValidation,@Error,"Stage to store result in does not exist{0}" EXEC chk 14,@StageValidation,@Error,"Decision expression does not result in a Flag value" EXEC chk 15,@StageValidation,@Error,"The chosen action in row {0} is not permitted for the corresponding element type" EXEC chk 16,@StageValidation,@Warning,"Row {0} contains an action which is outdated. Please consider updating." EXEC chk 17,@StageValidation,@Error,"Internal Error: No type information found on the element in row {0}." EXEC chk 18,@StageValidation,@Error,"There is no action selected in row {0}" EXEC chk 19,@StageValidation,@Error,"Failed to find referenced application element in row {0}. Element ID is {1}" EXEC chk 20,@StageValidation,@Error,"No application element chosen in row {0}" EXEC chk 21,@StageValidation,@Error,"Expression evaluates to the wrong datatype" EXEC chk 22,@StageValidation,@Warning,"Expression{0} is valid, but its data type cannot be resolved until runtime" EXEC chk 23,@StageValidation,@Error,"Invalid expression{0} - {1}" EXEC chk 24,@StageValidation,@Error,"Expression{0} is blank" EXEC chk 25,@StageValidation,@Error,"Block overlaps another block" EXEC chk 26,@StageValidation,@Error,"Stage is only partially within a block" EXEC chk 27,@StageValidation,@Warning,"Page ''{0}'' is not called by any other page" EXEC chk 28,@StageValidation,@Error,"Resume stage is not in a recovery section" EXEC chk 29,@FlowValidation,@Error,"Recovery stage is linked back to main process" EXEC chk 30,@StageValidation,@Error,"Exception stage wants to use existing exception information, but there can be no existing exception there" EXEC chk 31,@StageValidation,@Error,"Wrong type of parameter" EXEC chk 32,@StageValidation,@Warning,"Blank value supplied to input parameter ''{0}''" EXEC chk 33,@StageValidation,@Error,"Bad map type for an expression-type parameter" EXEC chk 34,@StageValidation,@Error,"Failed to validate input expression to {0}parameter ''{1}'' - {2}" EXEC chk 35,@StageValidation,@Error,"Expression to {0}parameter ''{1}'' results in a bad data type - {2}" EXEC chk 36,@StageValidation,@Warning,"Expression uses the function ''{0}'', which is deprecated" EXEC chk 37,@StageValidation,@Warning,"Failed to determine the data type of the expression to input parameter ''{0}''" EXEC chk 38,@StageValidation,@Error,"Bad map type for a stage-type parameter" EXEC chk 39,@StageValidation,@Error,"Data item to Store In for {0}parameter ''{1}'' does not exist" EXEC chk 40,@StageValidation,@Error,"Data item to Store In for {0}parameter ''{1}'' is out of scope" EXEC chk 41,@StageValidation,@Error,"Collection mismatch for {0}parameter ''{1}'': {2}" EXEC chk 42,@StageValidation,@Error,"Cannot store data in an environment variable" EXEC chk 43,@StageValidation,@Error,"No ''Store In'' mapping set for {0}parameter ''{1}''" EXEC chk 44,@StageValidation,@Error,"Expression is not valid{0} - {1}" EXEC chk 45,@StageValidation,@Warning,"Expression{0} uses the function {1}, which is deprecated" EXEC chk 46,@StageValidation,@Error,"Blank expression{0}" EXEC chk 47,@StageValidation,@Error,"Can not determine resulting data type of expression" EXEC chk 48,@StageValidation,@Warning,"Expression uses the function ''{0}'', which is deprecated" EXEC chk 49,@StageValidation,@Error,"Invalid expression" EXEC chk 50,@StageValidation,@Error,"Blank decision expression" EXEC chk 51,@FlowValidation,@Error,"No link when the decision is True" EXEC chk 52,@FlowValidation,@Error,"Invalid link for the True result" EXEC chk 53,@FlowValidation,@Error,"True link goes to a different page" EXEC chk 54,@FlowValidation,@Error,"No link when the decision is False" EXEC chk 55,@FlowValidation,@Error,"Invalid link for the False result" EXEC chk 56,@FlowValidation,@Error,"False link goes to a different page" EXEC chk 57,@FlowValidation,@Error,"Missing link" EXEC chk 58,@StageValidation,@Warning,"Stage has blank name" EXEC chk 59,@StageValidation,@Error,"Invalid expression in field Exception Detail - {0}" EXEC chk 60,@StageValidation,@Error,"Invalid data type match in row {0}." EXEC chk 61,@StageValidation,@Error,"The stage referenced in row {0} is out of scope." EXEC chk 62,@StageValidation,@Error,"The stage referenced in row {0} does not exist." EXEC chk 63,@StageValidation,@Error,"The element referenced in row {0} has no data type." EXEC chk 64,@StageValidation,@Error,"Failed to find referenced application element in row {0}. Element ID is {1}" EXEC chk 65,@StageValidation,@Warning,"The stage calls a process with parameter ''{0}'' which is not defined in the stage" EXEC chk 66,@StageValidation,@Warning,"The Page Reference stage provides a value for the input parameter ''{0}'' which is no longer defined by the target page." EXEC chk 67,@StageValidation,@Error,"The Page Reference stage provides a mapping for the Output parameter ''{0}'' which is no longer defined by the target page." EXEC chk 68,@StageValidation,@Error,"Row {0} does not have a valid target element" EXEC chk 69,@StageValidation,@Error,"Row {0} does not specify a condition" EXEC chk 70,@StageValidation,@Warning,"Row {0} contains a condition which is outdated. Please consider updating." EXEC chk 71,@StageValidation,@Error,"The timeout expression on this wait stage contains an error" EXEC chk 72,@StageValidation,@Error,"Row {0} has no application element set" EXEC chk 73,@StageValidation,@Warning,"Blank value supplied to input parameter ''{0}''{1}" EXEC chk 74,@StageValidation,@Error,"Failed to validate input expression to parameter ''{0}''{2} - {1}" EXEC chk 75,@StageValidation,@Error,"Expression to parameter ''{0}''{2} results in a bad data type - {1}" EXEC chk 76,@StageValidation,@Warning,"Failed to determine the data type of the expression to input parameter ''{0}''{1}" EXEC chk 77,@StageValidation,@Error,"Row {0} does not have a condition which is appropriate to the target element" EXEC chk 78,@StageValidation,@Error,"Row {0} has no read action defined." EXEC chk 79,@StageValidation,@Error,"The chosen read action in row {0} is not permitted for the corresponding element type" EXEC chk 80,@StageValidation,@Warning,"Row {0} contains an action which is outdated. Please consider updating." EXEC chk 81,@StageValidation,@Error,"Row {0} has an invalid store in location - the stage ''{1}'' does not exist." EXEC chk 82,@StageValidation,@Error,N''Row {0} has an invalid store in location - the collection stage ''''{1}'''' has some fields defined, whereas an empty (dynamic) collection is required.'' EXEC chk 83,@StageValidation,@Error,"Row {0} has a blank store in location" EXEC chk 84,@StageValidation,@Error,"Row {0} has an invalid store in location - the stage ''{1}'' cannot be found.{2}" EXEC chk 85,@StageValidation,@Error,"Row {0} has an invalid store in location - the stage ''{1}'' is located on another page and is marked as hidden." EXEC chk 86,@StageValidation,@Error,"Row {0} does not refer to a valid application element" EXEC chk 87,@StageValidation,@Error,"Row {0} supplies an expression to argument ''{1}'' which evaluates to the wrong datatype" EXEC chk 88,@StageValidation,@Warning,"Row {0} supplies an expression to argument ''{1}'' which is valid, but whose data type cannot be resolved until runtime" EXEC chk 89,@StageValidation,@Error,"Row {0} supplies an invalid expression to argument ''{1}''" EXEC chk 90,@StageValidation,@Error,"Row {0} supplies a blank expression to argument ''{1}''" EXEC chk 91,@StageValidation,@Error,"Row {0} does not supply a value to the compulsory parameter ''{1}''" EXEC chk 92,@StageValidation,@Error,"Row {0} contains an argument ''{1}'' that is not defined in the application model" EXEC chk 93,@StageValidation,@Error,"Parameter for attribute ''{0}'' in row {1} contains an invalid expression" EXEC chk 94,@StageValidation,@Error,"Missing element parameter for attribute ''{0}'' in row {1}" EXEC chk 95,@StageValidation,@Error,"The data item ''{0}'' on page ''{1}'' conflicts with the data item ''{2}'' on page ''{3}''" EXEC chk 96,@StageValidation,@Error,"Data item does not yet have a data type" EXEC chk 97,@StageValidation,@Error,"The Action has no Business Object (or Action) set." EXEC chk 98,@StageValidation,@Error,"The Action refers to the Business Object ''{0}'' which does not seem to be installed." EXEC chk 99,@StageValidation,@Error,"The referenced business object has been retired." EXEC chk 100,@StageValidation,@Error,N''The Action refers to the action ''''{0}'''' within the Business Object ''''{1}'''' but this Business Object does not contain an action with that name.'' EXEC chk 101,@FlowValidation,@Error,"Invalid link" EXEC chk 102,@FlowValidation,@Error,"Link to a different page" EXEC chk 103,@FlowValidation,@Error,"Missing group ID" EXEC chk 104,@FlowValidation,@Error,"Missing start stage for loop" EXEC chk 105,@FlowValidation,@Error,"Loop start is on a different page" EXEC chk 106,@FlowValidation,@Error,"Missing group ID on loop start stage" EXEC chk 107,@FlowValidation,@Error,"Missing end stage for loop" EXEC chk 108,@FlowValidation,@Error,"Loop end is on a different page" EXEC chk 109,@StageValidation,@Error,"The Page Reference stage does not refer to any page." EXEC chk 110,@StageValidation,@Error,"The Page Reference stage refers to a page which does not exist." EXEC chk 111,@StageValidation,@Error,"The Page Reference stage does not acknowledge the input parameter ''{0}'' defined by the target page." EXEC chk 112,@StageValidation,@Error,"The Page Reference stage does not acknowledge the output parameter ''{0}'' defined by the target page." EXEC chk 113,@StageValidation,@Error,"Collection field definition ''{0}'' has an invalid name" EXEC chk 114,@StageValidation,@Error,"Initial value field ''{0}'' has an invalid name" EXEC chk 115,@StageValidation,@Error,"Data item refers to a missing environment variable ''{0}''" EXEC chk 116,@StageValidation,@Error,"Undefined loop type" EXEC chk 117,@StageValidation,@Error,"Unrecognised loop type" EXEC chk 118,@StageValidation,@Error,"No collection set for loop stage" EXEC chk 119,@StageValidation,@Error,"Can not find collection stage ''{0}'' referenced in loop stage" EXEC chk 120,@StageValidation,@Error,"Loop stages references a collection which is not accessible - it is private and resides on another page" EXEC chk 121,@StageValidation,@Error,"The Process stage has not yet set the subprocess." EXEC chk 122,@StageValidation,@Error,"The Process stage references a subprocess which has been retired." EXEC chk 123,@StageValidation,@Error,"Compiler warning at line {0}: {1}" EXEC chk 124,@StageValidation,@Error,"Compiler error at line {0}: {1}" EXEC chk 125,@StageValidation,@Error,"Compiler warning at top section line {0}: {1}" EXEC chk 126,@StageValidation,@Error,"Compiler error at top section line {0}: {1}" INSERT INTO BPADBVersion VALUES ( ''137'', GETUTCDATE(), ''db_upgradeR137.sql UTC'', ''Add tables for process validation improvement'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='138') begin exec('IF OBJECT_ID(''chk'') IS NOT NULL DROP PROC chk ')exec('')exec('CREATE PROC chk @id int,@cat int,@typeid int,@msg nvarchar(255) AS insert into BPAValCheck (checkid,catid,typeid,description) values (@id,@cat,@typeid,@msg) ')exec('')exec('DECLARE @StageValidation int SET @StageValidation=0 DECLARE @FlowValidation int SET @FlowValidation=1 DECLARE @DocumentationControl int SET @DocumentationControl=2 DECLARE @Error int SET @Error=0 DECLARE @Warning int SET @Warning=1 DECLARE @Advice int SET @Advice=2 EXEC chk 128,@StageValidation,@Error,"Expression{0} uses Exception function but is not in a Recovery section" DELETE from BPAValCheck WHERE checkid = 0 DELETE from BPAValCheck WHERE checkid = 1 DELETE from BPAValCheck WHERE checkid = 2 DELETE from BPAValCheck WHERE checkid = 14 DELETE from BPAValCheck WHERE checkid = 32 DELETE from BPAValCheck WHERE checkid = 34 DELETE from BPAValCheck WHERE checkid = 35 DELETE from BPAValCheck WHERE checkid = 36 DELETE from BPAValCheck WHERE checkid = 37 DELETE from BPAValCheck WHERE checkid = 44 DELETE from BPAValCheck WHERE checkid = 46 DELETE from BPAValCheck WHERE checkid = 47 DELETE from BPAValCheck WHERE checkid = 48 DELETE from BPAValCheck WHERE checkid = 49 DELETE from BPAValCheck WHERE checkid = 50 DELETE from BPAValCheck WHERE checkid = 59 DELETE from BPAValCheck WHERE checkid = 71 DELETE from BPAValCheck WHERE checkid = 73 DELETE from BPAValCheck WHERE checkid = 74 DELETE from BPAValCheck WHERE checkid = 75 DELETE from BPAValCheck WHERE checkid = 76 DELETE from BPAValCheck WHERE checkid = 87 DELETE from BPAValCheck WHERE checkid = 88 DELETE from BPAValCheck WHERE checkid = 89 DELETE from BPAValCheck WHERE checkid = 93 UPDATE BPAValCheck SET typeid=@Warning WHERE checkid = 43 INSERT INTO BPADBVersion VALUES ( ''138'', GETUTCDATE(), ''db_upgradeR138.sql UTC'', ''Validation updates'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='139') begin exec('IF OBJECT_ID(''chk'') IS NOT NULL DROP PROC chk ')exec('')exec('CREATE PROC chk @id int,@cat int,@typeid int,@msg nvarchar(255) AS insert into BPAValCheck (checkid,catid,typeid,description) values (@id,@cat,@typeid,@msg) ')exec('')exec('DECLARE @StageValidation int SET @StageValidation=0 DECLARE @FlowValidation int SET @FlowValidation=1 DECLARE @DocumentationControl int SET @DocumentationControl=2 DECLARE @Error int SET @Error=0 DECLARE @Warning int SET @Warning=1 DECLARE @Advice int SET @Advice=2 DELETE from BPAValCheck WHERE checkid=39 DELETE from BPAValCheck WHERE checkid=40 DELETE from BPAValCheck WHERE checkid=42 DELETE from BPAValCheck WHERE checkid=43 UPDATE BPAValCheck SET description=''Collection mismatch{0}: {1}'' WHERE checkid=41 UPDATE BPAValCheck SET description=''Value to be stored is not compatible with destination{0}'' WHERE checkid=9 INSERT INTO BPADBVersion VALUES ( ''139'', GETUTCDATE(), ''db_upgradeR139.sql UTC'', ''Validation updates'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='140') begin exec('IF OBJECT_ID(''chk'') IS NOT NULL DROP PROC chk ')exec('')exec('CREATE PROC chk @id int,@cat int,@typeid int,@msg nvarchar(255) AS insert into BPAValCheck (checkid,catid,typeid,description) values (@id,@cat,@typeid,@msg) ')exec('')exec('DECLARE @StageValidation int SET @StageValidation=0 DECLARE @FlowValidation int SET @FlowValidation=1 DECLARE @DocumentationControl int SET @DocumentationControl=2 DECLARE @Error int SET @Error=0 DECLARE @Warning int SET @Warning=1 DECLARE @Advice int SET @Advice=2 EXEC chk 129,@DocumentationControl,@Warning,"Action stage has no description" EXEC chk 130,@DocumentationControl,@Advice,"Application element with dynamic attributes has no notes" EXEC chk 131,@DocumentationControl,@Advice,"No preconditions are defined" EXEC chk 132,@DocumentationControl,@Advice,"No postconditions are defined" EXEC chk 133,@DocumentationControl,@Advice,"No description given for parameter ''{0}''" EXEC chk 134,@StageValidation,@Error,"Referenced subprocess does not exist" INSERT INTO BPADBVersion VALUES ( ''140'', GETUTCDATE(), ''db_upgradeR140.sql UTC'', ''Validation updates'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='141') begin exec('DECLARE @NewIndex BIGINT SET @NewIndex= 1 DECLARE @Count BIGINT SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission (Name,PermissionID) VALUES (''Audit - View Design Controls'', @NewIndex) UPDATE BPAUser SET Permissions = Permissions & (~@NewIndex) UPDATE BPAPermission set PermissionID = PermissionID | @NewIndex WHERE Name=''System Manager'' UPDATE BPARole set RolePermissions = RolePermissions | @NewIndex WHERE RoleName=''System Administrator'' SET @Count = 1 WHILE @Count > 0 BEGIN SELECT @Count = COUNT(PermissionID) FROM BPAPermission WHERE PermissionID = @NewIndex IF @Count > 0 SET @NewIndex = 2 * @NewIndex END INSERT INTO BPAPermission (Name,PermissionID) VALUES (''Audit - Configure Design Controls'', @NewIndex) UPDATE BPAUser SET Permissions = Permissions & (~@NewIndex) UPDATE BPAPermission set PermissionID = PermissionID | @NewIndex WHERE Name=''System Manager'' UPDATE BPARole set RolePermissions = RolePermissions | @NewIndex WHERE RoleName=''System Administrator'' INSERT INTO BPADBVersion VALUES ( ''141'', GETUTCDATE(), ''db_upgradeR141.sql UTC'', ''Validation permission updates'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='142') begin exec('create table BPAPackageFont ( packageid int not null constraint FK_BPAPackageFont_BPAPackage foreign key references BPAPackage(id) on delete cascade, name varchar(255) not null constraint FK_BPAPackageFont_BPAFont foreign key references BPAFont(name) on delete cascade on update cascade, constraint PK_BPAPackageFont primary key (packageid, name) ) INSERT INTO BPADBVersion VALUES ( ''142'', GETUTCDATE(), ''db_upgradeR142.sql UTC'', ''Adds fonts to packages / releases'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='143') begin exec('insert into BPAPermission (permissionid, name) select 0x0000000000008000, ''View Release Manager'' union all select 0x0100000000000000, ''Create/Edit Package'' union all select 0x0200000000000000, ''Create Release'' union all select 0x0400000000000000, ''Delete Package'' union all select 0x0700000000008000, ''Release Manager'' update BPARole set RolePermissions = RolePermissions | 0x0700000000008000 where RoleName = ''System Administrator'' update BPAUser set permissions = permissions & ~cast(0x0700000000008000 as bigint) INSERT INTO BPADBVersion VALUES ( ''143'', GETUTCDATE(), ''db_upgradeR143.sql UTC'', ''Adds fonts to packages / releases'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='144') begin exec('UPDATE BPAPermission set Name=''Processes - Configure Environment Variables'' WHERE Name=''Modify Environment Variables'' insert into BPAPermission (permissionid, name) select 0x0800000000000000, ''Processes - View Environment Variables'' union all select 0x1000000000000000, ''Business Objects - Configure Environment Variables'' union all select 0x2000000000000000, ''Business Objects - View Environment Variables'' update BPAPermission set PermissionID = PermissionID | 0x3800000000000000 where Name = ''System Manager'' update BPARole set RolePermissions = RolePermissions | 0x3800000000000000 where RoleName = ''System Administrator'' update BPAUser set permissions = permissions & ~cast(0x3800000000000000 as bigint) INSERT INTO BPADBVersion VALUES ( ''144'', GETUTCDATE(), ''db_upgradeR144.sql UTC'', ''Correct permissions for environment variables'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='145') begin exec('alter table BPARelease add local bit not null constraint DEF_BPARelease_local default 1; INSERT INTO BPADBVersion VALUES ( ''145'', GETUTCDATE(), ''db_upgradeR145.sql UTC'', ''Adds support for storing imported releases / packages'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='146') begin exec('alter table BPAValCheck add enabled bit not null constraint DEF_BPAValCheck_enabled default 1; INSERT INTO BPADBVersion VALUES ( ''146'', GETUTCDATE(), ''db_upgradeR146.sql UTC'', ''Adds enabling/disabling of individual validation checks'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='147') begin exec('update BPAValCheck set description = ''Application element "{0}" has dynamic attributes but no notes'' where checkid = 130 INSERT INTO BPADBVersion VALUES ( ''147'', GETUTCDATE(), ''db_upgradeR147.sql UTC'', ''Adds element name to a validation check'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='148') begin exec('alter table BPAResource add logtoeventlog bit not null constraint DEF_BPAResource_logtoeventlog default 1 INSERT INTO BPADBVersion VALUES ( ''148'', GETUTCDATE(), ''db_upgradeR148.sql UTC'', ''Adds option for a resource to log to event log'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='149') begin exec('declare @perm bigint set @perm = 0x4000000000000000 insert into BPAPermission (permissionid, name) values (@perm, ''System - Fonts'') update BPAPermission set permissionid = permissionid | @perm where name = ''System Manager'' update BPARole set rolepermissions = rolepermissions | @perm where rolename = ''System Administrator'' INSERT INTO BPADBVersion VALUES ( ''149'', GETUTCDATE(), ''db_upgradeR149.sql UTC'', ''Adds permission to use the Fonts UI'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='150') begin exec('insert into BPAValCheck (checkid, catid, typeid, description) select 135, 0, 1, ''No ''''Store In'''' mapping set{0}'' union all select 136, 0, 1, ''Blank value supplied{0}'' union all select 137, 2, 2, ''Published action does not contain a description{0}'' update BPAValCheck set typeid=2 where checkid=129 INSERT INTO BPADBVersion VALUES ( ''150'', GETUTCDATE(), ''db_upgradeR150.sql UTC'', ''Adds missing validation checks'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='151') begin exec('if not exists ( select * from sys.indexes where name = ''Index_BPAWorkQueueItem_priorityloadedlockedfinished'') begin declare @sver nvarchar(128) declare @ver int set @sver = cast(serverproperty(''ProductVersion'') as nvarchar) set @ver = convert(int, substring(@sver, 1, charindex(''.'', @sver) - 1)) if @ver > 8 exec('' create index Index_BPAWorkQueueItem_priorityloadedlockedfinished on BPAWorkQueueItem ( priority, loaded, ident, locked, finished ) include ( queueident, exceptionreasonvarchar ) '') end INSERT INTO BPADBVersion VALUES ( ''151'', GETUTCDATE(), ''db_upgradeR151.sql UTC'', ''Adds index on work queue item table to avoid deadlocks'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='152') begin exec('if not exists ( select * from sys.indexes where name = ''Index_BPAWorkQueueItemTag_queueitemident'' ) create index Index_BPAWorkQueueItemTag_queueitemident on BPAWorkQueueItemTag(queueitemident) if not exists ( select * from sys.indexes where name = ''Index_BPAWorkQueueItem_itemid_attempt'' ) create index Index_BPAWorkQueueItem_itemid_attempt on BPAWorkQueueItem(id, attempt) insert into BPADBVersion values ( ''152'', GETUTCDATE(), ''db_upgradeR152.sql UTC'', ''Adds further indexes to queue / tag tables'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='153') begin exec('create table BPAPackageCalendar ( packageid int not null constraint FK_BPAPackageCalendar_BPAPackage foreign key references BPAPackage(id) on delete cascade, calendarid int not null constraint FK_BPAPackageCalendar_BPACalendar foreign key references BPACalendar(id) on delete cascade, constraint PK_BPAPackageCalendar primary key (packageid, calendarid) ) create table BPAOldPassword( id int identity not null primary key, userid uniqueidentifier not null constraint fk_bpaoldpassword_bpauser foreign key references bpauser(userid) on delete cascade, password varchar(128) null, lastuseddate datetime not null ) alter table BPAPasswordRules add norepeats bit not null default 0, norepeatsdays bit not null default 0, numberofrepeatsordays int not null default 0 INSERT INTO BPADBVersion VALUES ( ''153'', GETUTCDATE(), ''db_upgradeR153.sql UTC'', ''Adds tables supporting standalone calendars in packages and constraints on previous passwords'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='154') begin exec('alter table BPACredentials alter column password text not null INSERT INTO BPADBVersion VALUES ( ''154'', GETUTCDATE(), ''db_upgradeR154.sql UTC'', ''Change data type of password field in BPACredentials'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='155') begin exec('declare @prime table (id uniqueidentifier not null primary key) declare @clone table ( ident int not null identity(1,1) primary key, cloneid uniqueidentifier not null unique, primeid uniqueidentifier not null ) insert into @clone (cloneid,primeid) select resourceid, newid() from BPAResource; delete from @clone; insert into @prime select a.primeid from ( select distinct r2.resourceid as primeid from BPAResource r1 join BPAResource r2 on r1.name = r2.name and r1.lastupdated < r2.lastupdated ) a where not exists ( select 1 from BPAResource ir1 join BPAResource ir2 on ir1.name = ir2.name and ir1.lastupdated < ir2.lastupdated where ir1.resourceid = a.primeid ) insert into @clone (primeid, cloneid) select p.id, r2.resourceid from @prime p join BPAResource r1 on p.id = r1.resourceid join BPAResource r2 on r1.name = r2.name where r2.resourceid != p.id; update r set r.name = r.name + ''-'' + cast(c.ident as varchar(31)), r.attributeid = (r.attributeid | 1) from BPAResource r join @clone c on r.resourceid = c.cloneid; alter table BPAResource add constraint UNQ_BPAResource_name unique (name); INSERT INTO BPADBVersion VALUES ( ''155'', GETUTCDATE(), ''db_upgradeR155.sql UTC'', ''Adds unique constraint to resource name'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='156') begin exec('ALTER TABLE BPASysConfig DROP COLUMN ArchivingInterval; ALTER TABLE BPASysConfig DROP COLUMN ArchivingTime; ALTER TABLE BPASysConfig DROP COLUMN ArchivingDayOfMonth; ALTER TABLE BPASysConfig DROP COLUMN ArchivingMinLogAgeLimit; ALTER TABLE BPASysConfig DROP COLUMN ArchivingMachineName; ALTER TABLE BPASysConfig ADD ArchivingMode integer NOT NULL DEFAULT 0; ALTER TABLE BPASysConfig ADD ArchivingLastAuto datetime NULL; ALTER TABLE BPASysConfig ADD ArchivingFolder text NOT NULL DEFAULT ''''; ALTER TABLE BPASysConfig ADD ArchivingAge text NOT NULL DEFAULT ''6m''; ALTER TABLE BPASysConfig Add ArchivingDelete bit NOT NULL DEFAULT 0; ALTER TABLE BPASysConfig ADD ArchivingResource uniqueidentifier, CONSTRAINT [FK_BPASysconfig_BPAResource] FOREIGN KEY ( ArchivingResource ) REFERENCES BPAResource ( ResourceID ); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''156'', GETUTCDATE(), ''db_upgradeR156.sql UTC'', ''Update BPASysConfig archiving columns'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='157') begin exec('alter table BPAScheduleLog add constraint UNQ_BPAScheduleLog_scheduleid_time unique nonclustered (scheduleid, instancetime); alter table BPAScheduleLog add servername varchar(255) null, heartbeat datetime null; INSERT INTO BPADBVersion VALUES ( ''157'', GETUTCDATE(), ''db_upgradeR157.sql UTC'', ''Updates BPAScheduleLog to allow multiple active schedulers'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='158') begin exec('declare @sver nvarchar(128) declare @ver int set @sver = cast(serverproperty(''ProductVersion'') as nvarchar) set @ver = convert(int, substring(@sver, 1, charindex(''.'', @sver) - 1)) if @ver > 8 exec('' create index IX_BPAScheduleLogEntry_logid_entrytype on BPAScheduleLogEntry(schedulelogid, entrytype) include (entrytime, terminationreason) '') ')exec('')exec('create view BPVAnnotatedScheduleLog as select l.id, l.scheduleid, l.firereason, l.instancetime, l.servername, l.heartbeat, estart.entrytime as "starttime", efin.entrytime as "endtime", efin.entrytype as "endtype", efin.terminationreason as "endreason" from BPAScheduleLog l join BPAScheduleLogEntry estart on estart.schedulelogid = l.id and estart.entrytype = 0 left join BPAScheduleLogEntry efin on efin.schedulelogid = l.id and efin.entrytype in (1,2) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''158'', GETUTCDATE(), ''db_upgradeR158.sql UTC'', ''Creates an annotated view of the schedule log'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='159') begin exec('alter table BPAWorkQueue add encryptname varchar(255) null INSERT INTO BPADBVersion VALUES ( ''159'', GETUTCDATE(), ''db_upgradeR159.sql UTC'', ''Adds encryption key to work queues'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='160') begin exec('alter table BPATask add failfastonerror bit not null constraint DEF_BPATask_failfastonerror default 1 INSERT INTO BPADBVersion VALUES ( ''160'', GETUTCDATE(), ''db_upgradeR160.sql UTC'', ''Adds failfastonerror field to BPATask'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='161') begin exec('alter table BPAResource add permittedroles bigint not null default -1; insert into BPADBVersion values ( ''161'', GETUTCDATE(), ''db_upgradeR161.sql UTC'', ''Adds permittedroles bitmask to BPAResource'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='162') begin exec('drop index Index_SessionStageType on BPASessionLog create index Index_SessionStageType on BPASessionLog(sessionnumber, stagetype) insert into BPADBVersion values ( ''162'', GETUTCDATE(), ''db_upgradeR162.sql UTC'', ''Swaps order of sessionnumber index on BPASessionLog'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='163') begin exec('update BPAPublicHoliday set name=''New Year''''s Day'' where id=3; update BPAPublicHoliday set name=''Early May Bank Holiday'' where id=8; insert into BPAPublicHoliday (id, name, relativetoholiday, relativedaydiff) values (19, ''St Stephen''''s Day'', 2, 1); declare @eire int set @eire = (select id from BPAPublicHolidayGroup where name = ''Republic of Ireland'') delete from BPAPublicHolidayGroupMember where publicholidaygroupid = @eire and publicholidayid = 18; insert into BPAPublicHolidayGroupMember (publicholidaygroupid, publicholidayid) values (@eire, 19); update wd set wd.publicholidayid = 19 from BPAPublicHolidayWorkingDay wd join BPACalendar c on wd.calendarid = c.id where c.publicholidaygroupid = @eire and wd.publicholidayid = 18; insert into BPADBVersion values ( ''163'', GETUTCDATE(), ''db_upgradeR163.sql UTC'', ''Corrects names of public holidays'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='164') begin exec('alter table BPAProcess alter column name varchar(128) collate DATABASE_DEFAULT null alter table BPAProcess alter column processtype varchar(1) collate DATABASE_DEFAULT null alter table BPAProcess alter column description varchar(1000) collate DATABASE_DEFAULT null alter table BPAProcess alter column version varchar(20) collate DATABASE_DEFAULT null alter table BPAProcess add [__temp] text ')exec('')exec('update BPAProcess set [__temp] = processxml alter table BPAProcess drop column processxml ')exec('')exec('alter table BPAProcess add processxml text ')exec('')exec('update BPAProcess set processxml = [__temp] alter table BPAProcess drop column [__temp] ')exec('')exec('alter table BPAProcessBackup add [__temp] text ')exec('')exec('update BPAProcessBackup set [__temp] = processxml alter table BPAProcessBackup drop column processxml ')exec('')exec('alter table BPAProcessBackup add processxml text ')exec('')exec('update BPAProcessBackup set processxml = [__temp] alter table BPAProcessBackup drop column [__temp] ')exec('')exec('declare @droppersql varchar(255) set @droppersql = ''alter table BPAProcessGroup drop constraint ['' + ( select name from sysobjects where sysobjects.xtype = ''UQ'' AND sysobjects.parent_obj= OBJECT_ID(N''BPAProcessGroup'') ) + '']''; exec (@droppersql); ')exec('')exec('alter table BPAProcessGroup alter column GroupName varchar(32) COLLATE DATABASE_DEFAULT NOT NULL ')exec('')exec('alter table BPAProcessGroup add constraint UQ_BPAProcessGroup_GroupName unique (GroupName); insert into BPADBVersion values ( ''164'', GETUTCDATE(), ''db_upgradeR164.sql UTC'', ''Fixes specific collates on BPAProcess/BPAProcessBackup'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='165') begin exec('insert into BPAValCheck (checkid, catid, typeid, description, enabled) values (14, 0, 0, ''Stage to read value from does not exist{0}'', 1) insert into BPADBVersion values ( ''165'', GETUTCDATE(), ''db_upgradeR165.sql UTC'', ''Adds error message for missing data stage referred to from end stage'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='166') begin exec('ALTER TABLE BPASysConfig ALTER COLUMN LicenseKey text null INSERT INTO BPADBVersion VALUES ( ''166'', GETUTCDATE(), ''db_upgradeR166.sql UTC'', ''Expand field in BPASysConfig'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='167') begin exec('create table BPAWebServiceAsset ( serviceid uniqueidentifier not null constraint FK_BPAWebServiceAsset_BPAWebService foreign key references BPAWebService(serviceid) on delete cascade, assettype tinyint not null, assetxml ntext null ) ')exec('')exec('create clustered index Index_BPAWebServiceAsset_serviceid_assettype on BPAWebServiceAsset (serviceid, assettype) INSERT INTO BPADBVersion VALUES ( ''167'', GETUTCDATE(), ''db_upgradeR167.sql UTC'', ''Add BPAWebServiceAsset table'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='168') begin exec('alter table BPAProcess drop constraint FK_BPAProcess_DefaultRealTimeStatsView drop table BPAUserViewPreferencePerProcess; drop table BPARealTimeStatsView; alter table BPAProcess add wspublishname varchar(255) null; alter table BPAProcess drop column DefaultRealTimeStatsView; insert into BPAProcessAttribute (AttributeID, AttributeName) values (4, ''PublishWS'') ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''168'', GETUTCDATE(), ''db_upgradeR168.sql UTC'', ''Add web service publishing support to BPAProcess table'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='169') begin exec('if exists ( select * from sys.indexes where object_id = object_id(''BPATag'') and name = N''UNQ_BPATag_tag'' ) drop index UNQ_BPATag_tag on BPATag; alter table BPATag alter column tag nvarchar(255) not null create unique index UNQ_BPATag_tag on BPATag(tag); if exists ( select * from sys.indexes where object_id = object_id(''BPAWorkQueue'') and name = N''Index_name'' ) alter table BPAWorkQueue drop constraint Index_name; declare @unq nvarchar(255); set @unq = ( select i.name from sys.indexes i where i.is_primary_key = 0 and i.is_unique = 1 and object_name(i.object_id) = ''BPAWorkQueue'' ); if @unq is not null begin set @unq = ''alter table BPAWorkQueue drop constraint ['' + @unq + '']''; exec(@unq); end; alter table BPAWorkQueue alter column name nvarchar(255); alter table BPAWorkQueue add constraint Index_name unique nonclustered (name); if exists ( select * from sys.indexes where object_id = object_id(''BPAWorkQueueItem'') and name = N''INDEX_BPAWorkQueueItem_exceptionreasonvarchar'' ) drop index INDEX_BPAWorkQueueItem_exceptionreasonvarchar on BPAWorkQueueItem; if exists ( select * from sys.indexes where object_id = object_id(''BPAWorkQueueItem'') and name = N''Index_BPAWorkQueueItem_key'' ) drop index Index_BPAWorkQueueItem_key on BPAWorkQueueItem; if exists ( select * from sys.indexes where object_id = object_id(N''BPAWorkQueueItem'') and name = N''Index_BPAWorkQueueItem_priorityloadedlockedfinished'' ) drop index Index_BPAWorkQueueItem_priorityloadedlockedfinished on BPAWorkQueueItem; alter table BPAWorkQueueItem drop column exceptionreasonvarchar; alter table BPAWorkQueueItem add exceptionreasonvarchar as cast(exceptionreason as nvarchar(400)); alter table BPAWorkQueueItem alter column keyvalue nvarchar(255) not null create index Index_BPAWorkQueueItem_exceptionreasonvarchar on BPAWorkQueueItem(exceptionreasonvarchar) create index Index_BPAWorkQueueItem_key on BPAWorkQueueItem(keyvalue) create index Index_BPAWorkQueueItem_queuepriorityloaded on BPAWorkQueueItem (queueident, priority,loaded); alter table BPAWorkQueueItem add exceptionreasontag as cast(N''Exception: '' + replace(convert(nvarchar(400),exceptionreason), N'';'', N'':'') as nvarchar(415)) persisted create index Index_BPAWorkQueueItem_exceptionreasontag on BPAWorkQueueItem(exceptionreasontag) if exists ( select * from sys.indexes where object_id = object_id(''BPAWorkQueueItemTag'') and name = N''Index_Temp_BPAWorkQueueItemTag_tagid'' ) drop index Index_Temp_BPAWorkQueueItemTag_tagid on BPAWorkQueueItemTag; drop index PK_BPAWorkQueueItemTag on BPAWorkQueueItemTag; alter table BPAWorkQueueItemTag add constraint PK_BPAWorkQueueItemTag primary key clustered (tagid, queueitemident) with (ignore_dup_key = on); ')exec('')exec('alter view BPViewWorkQueueItemTag (queueitemident, tag) as select it.queueitemident, t.tag from BPAWorkQueueItemTag it join BPATag t on it.tagid = t.id union select i.ident, i.exceptionreasontag from BPAWorkQueueItem i where i.exception is not null; ')exec('')exec('create view BPViewWorkQueueItemTagBare (queueitemident, tag) as select it.queueitemident, t.tag from BPAWorkQueueItemTag it join BPATag t on it.tagid = t.id; ')exec('')exec('create table BPAEnvLock_new ( name nvarchar(255) not null constraint PK_BPAEnvLock_new primary key, token varchar(255) null, sessionid uniqueidentifier null constraint FK_BPAEnvLock_BPASession_new foreign key references BPASession(sessionid), locktime datetime null, comments varchar(1024) null ); insert into BPAEnvLock_new (name, token, sessionid, locktime, comments) select name, token, sessionid, locktime, comments from BPAEnvLock; drop table BPAEnvLock; exec sp_rename ''BPAEnvLock_new'', ''BPAEnvLock''; exec sp_rename ''PK_BPAEnvLock_new'', ''PK_BPAEnvLock''; exec sp_rename ''FK_BPAEnvLock_BPASession_new'', ''FK_BPAEnvLock_BPASession''; create index Index_BPAAlertEvent_subscriberuserid_subscriberdate on BPAAlertEvent (subscriberuserid, subscriberdate); INSERT INTO BPADBVersion VALUES ( ''169'', GETUTCDATE(), ''db_upgradeR169.sql UTC'', ''Various changes aimed at improving performance of long queries'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='170') begin exec('IF object_id(''PK_BPAExceptionType'') IS NULL ALTER TABLE BPAExceptionType ADD constraint PK_BPAExceptionType primary key (id); IF object_id(''PK_BPAStatistics'') IS NULL BEGIN ALTER TABLE BPAStatistics ALTER COLUMN sessionid uniqueidentifier NOT NULL; ALTER TABLE BPAStatistics ALTER COLUMN name varchar(50) NOT NULL; END ')exec('')exec('IF object_id(''PK_BPAStatistics'') IS NULL BEGIN ALTER TABLE BPAStatistics ADD constraint PK_BPAStatistics primary key (sessionid, name); END ')exec('')exec('IF object_id(''PK_BPAPasswordRules'') IS NULL alter table BPAPasswordRules ADD id int NOT NUll default 1 constraint PK_BPAPasswordRules primary key (id) IF object_id(''PK_BPAValActionMap'') IS NULL alter table BPAValActionMap ADD constraint PK_BPAValActionMap primary key (catid, typeid, actionid) IF not exists (SELECT * FROM sys.indexes WHERE name=''INDEX_BPAAuditEvents_eventdatetime'' AND object_id = OBJECT_ID(''BPAAuditEvents'')) create clustered index INDEX_BPAAuditEvents_eventdatetime on BPAAuditEvents(eventdatetime); create clustered index INDEX_BPAIntegerPref_prefid on BPAIntegerPref(prefid); create clustered index INDEX_BPAStringPref_prefid on BPAStringPref(prefid); create clustered index INDEX_BPAToolPosition_userid_name on BPAToolPosition(UserID, Name); INSERT INTO BPADBVersion VALUES ( ''170'', GETUTCDATE(), ''db_upgradeR170.sql UTC'', ''Updates for retrospective changes made under bug #8443'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='171') begin exec('delete from BPAStatus where type=''ENV''; insert into BPAStatus(statusid, type, description) values (6, ''RUN'', ''Archived''); ')exec('')exec('alter view BPVSessionInfo as select s.sessionid as "sessionid", s.sessionnumber as "sessionnumber", s.startdatetime as "startdatetime", s.enddatetime as "enddatetime", s.processid as "processid", p.name as "processname", s.starterresourceid as "starterresourceid", sr.name as "starterresourcename", s.starteruserid as "starteruserid", isnull(su.username, ''['' + su.systemusername + '']'') as "starterusername", s.runningresourceid as "runningresourceid", rr.name as "runningresourcename", s.runningosusername as "runningosusername", s.statusid as "statusid", s.startparamsxml as "startparamsxml", s.logginglevelsxml as "logginglevelsxml", s.sessionstatexml as "sessionstatexml" from BPASession s join BPAProcess p on s.processid = p.processid join BPAResource sr on s.starterresourceid = sr.resourceid join BPAResource rr on s.runningresourceid = rr.resourceid join BPAUser su on s.starteruserid = su.userid where s.statusid <> 6; ')exec('')exec('create view BPVSession as select * from BPASession where statusid <> 6; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''171'', GETUTCDATE(), ''db_upgradeR171.sql UTC'', ''Adds BPASession flag to indicate if it''''s been archived'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='172') begin exec('CREATE TABLE [BPAStatistics_new] ( sessionid uniqueidentifier NOT NULL, name varchar (50) NOT NULL, datatype varchar (32) NULL, value_text varchar (255) NULL, value_number float NULL, value_date datetime NULL, value_flag bit NULL, CONSTRAINT PK_BPAStatistics_new primary key (sessionid, name) ); insert into BPAStatistics_new (sessionid, name, datatype, value_text, value_number, value_date, value_flag) select sessionid, name, datatype, value_text, value_number, value_date, value_flag from BPAStatistics; drop table BPAStatistics; exec sp_rename ''BPAStatistics_new'', ''BPAStatistics''; exec sp_rename ''PK_BPAStatistics_new'', ''PK_BPAStatistics''; INSERT INTO BPADBVersion VALUES ( ''172'', GETUTCDATE(), ''db_upgradeR172.sql UTC'', ''Ensure correct index on BPAStatistics'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='173') begin exec('if object_id(''UNQ_BPACredentialsProcesses'') is null alter table BPACredentialsProcesses add constraint UNQ_BPACredentialsProcesses unique clustered(credentialid, processid); if object_id(''UNQ_BPACredentialsResources'') is null alter table BPACredentialsResources add constraint UNQ_BPACredentialsResources unique clustered(credentialid, resourceid); if object_id(''PK_BPAProcessMITemplate'') is null alter table BPAProcessMITemplate add constraint PK_BPAProcessMITemplate primary key(templatename, processid); INSERT INTO BPADBVersion VALUES ( ''173'', GETUTCDATE(), ''db_upgradeR173.sql UTC'', ''Adds clustered indexes to BPACredentialsProcesses, BPACredentialsResources and BPAProcessMITemplate'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='174') begin exec('ALTER TABLE BPACredentials ADD expirydate datetime NULL, invalid bit ')exec('')exec('UPDATE BPACredentials SET invalid=0 ')exec('')exec('CREATE TABLE BPACredentialsProperties ( id uniqueidentifier NOT NULL, credentialid uniqueidentifier NOT NULL, name nvarchar(255) NOT NULL, value nvarchar(max) NULL, CONSTRAINT PK_BPACredentialsProperties PRIMARY KEY CLUSTERED ( id ), CONSTRAINT Index_BPACredentialsProperties_credentialidname UNIQUE ( credentialid, name ), CONSTRAINT FK_BPACredentialsProperties_cred FOREIGN KEY ( credentialid ) REFERENCES BPACredentials ( id ) ) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''174'', GETUTCDATE(), ''db_upgradeR174.sql UTC'', ''Adds expiry date & invalid flag to Credentials and new table for Credential properties.'' ) ') end
if not exists (select 1 from BPADBVersion where dbversion='175') begin exec('ALTER procedure bpa_sp_dropdefault @tableName varchar(256), @columnName varchar(256) as if exists (select 1 from syscolumns where id = object_id(@tableName) and name=@columnName) begin declare @defaultName varchar(256) select @defaultName = name from sys.default_constraints where parent_object_id = object_id(@tableName) and col_name(parent_object_id, parent_column_id) = @columnName if @defaultName is not null exec(''alter table ['' + @tableName + ''] drop constraint '' + @defaultName) end ')exec('')exec('create table BPAPerm ( id int identity not null, name nvarchar(255) not null, constraint PK_BPAPerm primary key clustered (id) ); create unique index UNQ_BPAPerm_name on BPAPerm(name); create table BPAPermGroup ( id int identity not null, name nvarchar(255) not null, constraint PK_BPAPermGroup primary key clustered (id) ); create unique index UNQ_BPAPermGroup_name on BPAPermGroup(name); create table BPAPermGroupMember ( permgroupid int not null constraint FK_BPAPermGroupMember_BPAPermGroup foreign key references BPAPermGroup(id), permid int not null constraint FK_BPAPermGroupMember_BPAPerm foreign key references BPAPerm(id), constraint PK_BPAPermGroupMember primary key clustered (permgroupid, permid) ); create table BPAUserRole ( id int not null identity, name nvarchar(255) not null, ssogroup nvarchar(255) null, adhocuserid uniqueidentifier null, constraint PK_BPAUserRole primary key clustered (id) ); create unique index UNQ_BPAUserRole_name on BPAUserRole(name); create table BPAUserRolePerm ( userroleid int not null constraint FK_BPAUserRolePerm_BPAUserRole foreign key references BPAUserRole(id) on delete cascade, permid int not null constraint FK_BPAUserRolePerm_BPAPerm foreign key references BPAPerm(id), constraint PK_BPAUserRolePerm primary key clustered (permid, userroleid) ); create table BPAUserRoleAssignment ( userid uniqueidentifier not null constraint FK_BPAUserRoleAssignment_BPAUser foreign key references BPAUser(userid) on delete cascade, userroleid int not null constraint FK_BPAUserRoleAssignment_BPAUserRole foreign key references BPAUserRole(id) on delete cascade, constraint PK_BPAUserRoleAssignment primary key clustered (userid, userroleid) ); create table BPACredentialRole ( credentialid uniqueidentifier not null constraint FK_BPACredentialRole_BPACredential foreign key references BPACredentials (id) on delete cascade, userroleid int null constraint FK_BPACredentialRole_BPAUserRole foreign key references BPAUserRole (id) on delete cascade, constraint UNQ_BPACredentialRole unique clustered (credentialid, userroleid) ); create table BPAResourceRole ( resourceid uniqueidentifier not null constraint FK_BPAResourceRole_BPAResource foreign key references BPAResource (resourceid) on delete cascade, userroleid int null constraint FK_BPAResourceRole_BPAUserRole foreign key references BPAUserRole (id) on delete cascade constraint UNQ_BPAResourceRole unique clustered (resourceid, userroleid) ); ')exec('')exec('declare @groups table ( gpname varchar(255) not null, permname varchar(255) not null ); insert into @groups (gpname, permname) select p.name as "Group Name", p2.name as "Perm Name" from BPAPermission p join BPAPermission p2 on p.PermissionID!=p2.PermissionID and (p.PermissionID & p2.PermissionID)!=0 where (p.PermissionID & (p.PermissionID-1) != 0) and (p2.PermissionID & (p2.PermissionID-1) = 0); insert into BPAPerm (name) select distinct permname from @groups; insert into BPAPermGroup (name) select distinct gpname from @groups; insert into BPAPermGroupMember (permgroupid, permid) select pg.id, p.id from BPAPerm p cross join BPAPermGroup pg join @groups g on p.name = g.permname and pg.name = g.gpname order by pg.id, p.id; insert into BPAUserRole (name, ssogroup) select RoleName, SingleSignonUserGroup from BPARole; insert into BPAUserRolePerm (userroleid, permid) select ur.id, p.id from BPAUserRole ur join BPARole r on ur.name = r.RoleName join BPAPermission op on (r.RolePermissions & op.PermissionID) != 0 join BPAPerm p on p.name = op.Name insert into BPAUserRoleAssignment (userid, userroleid) select u.userid, ur.id from BPAUser u join BPARole r on (u.Roles & r.RoleID) != 0 join BPAUserRole ur on ur.name = r.RoleName declare @adhocs table ( userid uniqueidentifier not null, perm nvarchar(255) not null ); insert into @adhocs (userid, perm) select u.userid, p.Name from BPAUser u join BPAPermission p on (u.Permissions & p.PermissionID)!=0 where not exists ( select 1 from BPAUser u2 join BPARole r2 on (u2.Roles & r2.RoleID) != 0 join BPAPermission p2 on (r2.RolePermissions & p2.PermissionID) != 0 where u2.userid = u.userid and p.Name = p2.Name ); insert into BPAUserRole (name, adhocuserid) select distinct ''Auto-generated Adhoc Role for: '' + u.username, u.userid from BPAUser u join @adhocs a on u.userid = a.userid; insert into BPAUserRolePerm (userroleid, permid) select ur.id, p.id from @adhocs a join BPAUserRole ur on a.userid = ur.adhocuserid join BPAPerm p on a.perm = p.name; insert into BPAUserRoleAssignment (userid, userroleid) select adhocuserid, id from BPAUserRole where adhocuserid is not null; insert into BPACredentialRole (credentialid, userroleid) select c.id, ur.id from BPACredentials c join BPARole r on (c.roleid & r.RoleID) != 0 join BPAUserRole ur on ur.name = r.RoleName where c.roleid != -1 union all select c.id, null from BPACredentials c where c.roleid = -1; insert into BPAResourceRole (resourceid, userroleid) select res.resourceid, ur.id from BPAResource res join BPARole r on (res.permittedroles & r.RoleID) != 0 join BPAUserRole ur on ur.name = r.RoleName where res.permittedroles != -1 union all select res.resourceid, null from BPAResource res where res.permittedroles = -1; ')exec('')exec('alter table BPAUserRole drop column adhocuserid; exec bpa_sp_dropdefault ''BPAUser'', ''Permissions''; exec bpa_sp_dropdefault ''BPAUser'', ''Roles''; exec bpa_sp_dropdefault ''BPAResource'', ''permittedroles''; alter table BPAUser drop column Permissions; alter table BPAUser drop column Roles; alter table BPACredentials drop column roleid; alter table BPAResource drop column permittedroles; drop table BPARole; drop table BPAPermission; INSERT INTO BPADBVersion VALUES ( ''175'', GETUTCDATE(), ''db_upgradeR175.sql UTC'', ''Transplants the roles & permissions to a new structure'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='176') begin exec('alter table BPASysConfig add DependencyState int default 2 not null; ')exec('')exec('update BPASysConfig set DependencyState=0 where (select COUNT(processid) from BPAProcess) > 0; alter table BPAProcess add runmode int default 0 not null; create table BPAProcessIDDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessIDDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refProcessID uniqueidentifier not null, constraint PK_BPAProcessIDDependency primary key (id) ); create table BPAProcessNameDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessNameDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refProcessName nvarchar(128) not null, constraint PK_BPAProcessNameDependency primary key (id) ); create table BPAProcessActionDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessActionDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refProcessName nvarchar(128) not null, refActionName nvarchar(max) not null, constraint PK_BPAProcessActionDependency primary key (id) ); create table BPAProcessElementDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessElementDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refProcessName nvarchar(128) not null, refElementID uniqueidentifier not null, constraint PK_BPAProcessElementDependency primary key (id) ); create table BPAProcessWebServiceDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessWebServiceDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refServiceName nvarchar(128) not null, constraint PK_BPAProcessWebServiceDependency primary key (id) ); create table BPAProcessQueueDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessQueueDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refQueueName nvarchar(255) not null, constraint PK_BPAProcessQueueDependency primary key (id) ); create table BPAProcessCredentialsDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessCredentialsDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refCredentialsName nvarchar(255) not null, constraint PK_BPAProcessCredentialsDependency primary key (id) ); create table BPAProcessEnvironmentVarDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessEnvironmentVarDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refVariableName nvarchar(64) not null, constraint PK_BPAProcessEnvironmentVarDependency primary key (id) ); create table BPAProcessCalendarDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessCalendarDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refCalendarName nvarchar(128) not null, constraint PK_BPAProcessCalendarDependency primary key (id) ); create table BPAProcessFontDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessFontDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refFontName nvarchar(255) not null, constraint PK_BPAProcessFontDependency primary key (id) ); INSERT INTO BPADBVersion VALUES ( ''176'', GETUTCDATE(), ''db_upgradeR176.sql UTC'', ''Add new tables for Dependency Tracking'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='177') begin exec('create table BPAGroup ( id uniqueidentifier not null, treeid int not null, name nvarchar(255) not null, parentid uniqueidentifier null constraint FK_BPAGroup_BPAGroup foreign key references BPAGroup(id), constraint PK_BPAGroup primary key clustered (id) ); create table BPAGroupProcess ( groupid uniqueidentifier not null constraint FK_BPAGroupProcess_BPAGroup foreign key references BPAGroup(id) on delete cascade, processid uniqueidentifier not null constraint FK_BPAGroupProcess_BPAProcess foreign key references BPAProcess(processid) on delete cascade, constraint PK_BPAGroupProcess primary key clustered (groupid, processid) ); create table BPATile ( id uniqueidentifier not null, name nvarchar(255) not null, tiletype int not null, description nvarchar(255) null, autorefresh int not null, xmlproperties nvarchar(max) null, constraint PK_BPATile primary key clustered (id), constraint Index_BPATile_name unique (name) ); create table BPADashboard ( id uniqueidentifier not null, name nvarchar(255) not null, dashtype int not null, userid uniqueidentifier null constraint FK_BPADashboard_BPAUser foreign key references BPAUser(userid), constraint PK_BPADashboard primary key clustered (id) ); create table BPADashboardTile ( dashid uniqueidentifier not null constraint FK_BPADashboardTile_BPADashboard foreign key references BPADashboard(id) on delete cascade, tileid uniqueidentifier not null constraint FK_BPADashboardTile_BPATile foreign key references BPATile(id) on delete cascade, displayorder int not null, width int not null, height int not null, constraint PK_BPADashboardTile primary key clustered (dashid, tileid) ); create table BPAGroupTile ( groupid uniqueidentifier not null constraint FK_BPAGroupTile_BPAGroup foreign key references BPAGroup(id) on delete cascade, tileid uniqueidentifier not null constraint FK_BPAGroupTile_BPATile foreign key references BPATile(id) on delete cascade, constraint PK_GroupTile primary key clustered (groupid, tileid) ); declare @id int; insert into BPAPerm values(''Design Personal Dashboards''); insert into BPAPerm values(''Design Global Dashboards''); insert into BPAPerm values(''Create/Edit/Delete Tiles''); insert into BPAPerm values(''View Dashboards''); insert into BPAPerm values(''View Reports''); insert into BPAPermGroup values(''Review''); select @id = id from BPAPermGroup where name=''Review''; insert into BPAPermGroupMember select @id, a.id from BPAPerm a where a.name in (''Design Personal Dashboards'', ''Design Global Dashboards'', ''Create/Edit/Delete Tiles'', ''View Dashboards'', ''View Reports''); select @id = id from BPAUserRole where name=''System Administrator''; insert into BPAUserRolePerm select @id, a.id from BPAPerm a where a.name in (''Design Personal Dashboards'', ''Design Global Dashboards'', ''Create/Edit/Delete Tiles'', ''View Dashboards'', ''View Reports''); INSERT INTO BPADBVersion VALUES ( ''177'', GETUTCDATE(), ''db_upgradeR177.sql UTC'', ''Adds new table structure for generic groups and MI dashboards'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='178') begin exec('insert into BPAPerm (name) values(''Processes - Exposure''); insert into BPAPerm (name) values(''Business Objects - Exposure''); insert into BPAPerm (name) values(''Audit - Alerts''); insert into BPAPerm (name) values(''Workflow - Single Sign On''); declare @id int; select @id = id from BPAPermGroup where name=''System Manager''; insert into BPAPermGroupMember select @id, a.id from BPAPerm a where a.name in (''Processes - Exposure'', ''Business Objects - Exposure'', ''Audit - Alerts'', ''Workflow - Single Sign On''); select @id = id from BPAUserRole where name=''System Administrator''; insert into BPAUserRolePerm select @id, a.id from BPAPerm a where a.name in (''Processes - Exposure'', ''Business Objects - Exposure'', ''Audit - Alerts'', ''Workflow - Single Sign On''); INSERT INTO BPADBVersion VALUES ( ''178'', GETUTCDATE(), ''db_upgradeR178.sql UTC'', ''Adds new permissions for system manager'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='179') begin exec('create table BPAMIControl ( id int not null default 1, mienabled bit default 0, autorefresh bit default 0, refreshat datetime, lastrefresh datetime, refreshinprogress bit default 0, dailyfor int default 30, monthlyfor int default 6, constraint PK_BPAMIControl primary key clustered (id) ) create table BPMIUtilisationShadow ( sessionid uniqueidentifier not null, resourceid uniqueidentifier not null, processid uniqueidentifier not null, startdatetime datetime not null, enddatetime datetime null, constraint PK_BPMIUtilisationShadow primary key clustered (sessionid) ); create table BPMIUtilisationDaily ( reportdate smalldatetime not null, resourceid uniqueidentifier not null, processid uniqueidentifier not null, hr0 int null, hr1 int null, hr2 int null, hr3 int null, hr4 int null, hr5 int null, hr6 int null, hr7 int null, hr8 int null, hr9 int null, hr10 int null, hr11 int null, hr12 int null, hr13 int null, hr14 int null, hr15 int null, hr16 int null, hr17 int null, hr18 int null, hr19 int null, hr20 int null, hr21 int null, hr22 int null, hr23 int null, constraint PK_BPMIUtilisationDaily primary key clustered (reportdate,resourceid,processid) ); create table BPMIUtilisationMonthly ( reportyear int not null, reportmonth int not null, resourceid uniqueidentifier not null, processid uniqueidentifier not null, hr0 int null, hr1 int null, hr2 int null, hr3 int null, hr4 int null, hr5 int null, hr6 int null, hr7 int null, hr8 int null, hr9 int null, hr10 int null, hr11 int null, hr12 int null, hr13 int null, hr14 int null, hr15 int null, hr16 int null, hr17 int null, hr18 int null, hr19 int null, hr20 int null, hr21 int null, hr22 int null, hr23 int null, constraint PK_BPMIUtilisationMonthly primary key clustered (reportyear,reportmonth,resourceid,processid) ); create table BPMIProductivityShadow ( ident bigint identity(1,1) not null, eventdatetime datetime not null, queueident int not null, itemid uniqueidentifier not null, eventid int not null, worktime int null, elapsedtime int null, attempt int null, constraint PK_BPMIProductivityShadow primary key clustered (ident) ) create table BPMIProductivityDaily ( reportdate smalldatetime not null, queueident int not null, created int null, deferred int null, retried int null, exceptioned int null, completed int null, minworktime int null, avgworktime decimal(12,2) null, maxworktime int null, minelapsedtime int null, avgelapsedtime decimal(12,2) null, maxelapsedtime int null, minretries int null, avgretries decimal(12,2) null, maxretries int null, constraint PK_BPMIProductivityDaily primary key clustered (reportdate, queueident) ) create table BPMIProductivityMonthly ( reportyear int not null, reportmonth int not null, queueident int not null, created int null, deferred int null, retried int null, exceptioned int null, completed int null, minworktime int null, avgworktime decimal(12,2) null, maxworktime int null, minelapsedtime int null, avgelapsedtime decimal(12,2) null, maxelapsedtime int null, minretries int null, avgretries decimal(12,2) null, maxretries int null, constraint PK_BPMIProductivityMonthly primary key clustered (reportyear, reportmonth, queueident) ) insert into BPAMIControl (id) values (1); ')exec('')exec('if not exists (select * from sys.objects where type = ''P'' and name = ''usp_RefreshProductivityData'') exec(N''create procedure usp_RefreshProductivityData as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''usp_RefreshUtilisationData'') exec(N''create procedure usp_RefreshUtilisationData as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''usp_RefreshMI'') exec(N''create procedure usp_RefreshMI as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_WorkforceAvailability'') exec(N''create procedure BPDS_WorkforceAvailability as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_TotalAutomations'') exec(N''create procedure BPDS_TotalAutomations as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_LargestTables'') exec(N''create procedure BPDS_LargestTables as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_DailyUtilisation'') exec(N''create procedure BPDS_DailyUtilisation as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_ProcessUtilisationByHour'') exec(N''create procedure BPDS_ProcessUtilisationByHour as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_ResourceUtilisationByHour'') exec(N''create procedure BPDS_ResourceUtilisationByHour as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_AverageHandlingTime'') exec(N''create procedure BPDS_AverageHandlingTime as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_DailyProductivity'') exec(N''create procedure BPDS_DailyProductivity as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_FTEProductivityComparison'') exec(N''create procedure BPDS_FTEProductivityComparison as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_AverageRetries'') exec(N''create procedure BPDS_AverageRetries as begin set nocount on; end''); if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_Exceptions'') exec(N''create procedure BPDS_Exceptions as begin set nocount on; end''); ')exec('')exec('alter procedure usp_RefreshProductivityData @ReportDate datetime, @DaysToKeep int, @MonthsToKeep int as declare @ReportTo datetime; declare @DailyProductivity table ( queueident int, created int, deferred int, retried int, exceptioned int, completed int, minworktime int, avgworktime decimal(12,2), maxworktime int, minelapsedtime int, avgelapsedtime decimal(12,2), maxelapsedtime int, minretries int, avgretries decimal(12,2), maxretries int); set @ReportTo = DATEADD(DAY, 1, @ReportDate); insert into @DailyProductivity select queueident, SUM(case when eventid = 1 then 1 else 0 end), SUM(case when eventid = 3 then 1 else 0 end), SUM(case when eventid = 4 then 1 when eventid = 8 then 1 else 0 end), SUM(case when eventid = 6 then 1 else 0 end), SUM(case when eventid = 5 then 1 else 0 end), MIN(case when eventid = 5 then worktime end), AVG(case when eventid = 5 then CAST(worktime as float) end), MAX(case when eventid = 5 then worktime end), MIN(case when eventid = 5 then elapsedtime end), AVG(case when eventid = 5 then CAST(elapsedtime as float) end), MAX(case when eventid = 5 then elapsedtime end), MIN(case when eventid = 5 then attempt end), AVG(case when eventid = 5 then CAST(attempt as float) end), MAX(case when eventid = 5 then attempt end) from BPMIProductivityShadow where eventdatetime >= @ReportDate and eventdatetime < @ReportTo group by queueident; insert into BPMIProductivityDaily select @ReportDate, * from @DailyProductivity; update BPMIProductivityMonthly set created = m.created + d.created, deferred = m.deferred + d.deferred, retried = m.retried + d.retried, exceptioned = m.exceptioned + d.exceptioned, completed = m.completed + d.completed, minelapsedtime = (case when d.minelapsedtime < m.minelapsedtime then d.minelapsedtime else m.minelapsedtime end), avgelapsedtime = ((m.completed * m.avgelapsedtime) + (d.completed * d.avgelapsedtime)) / (m.completed + d.completed), maxelapsedtime = (case when d.maxelapsedtime > m.maxelapsedtime then d.maxelapsedtime else m.maxelapsedtime end), minworktime = (case when d.minworktime < m.minworktime then d.minworktime else m.minworktime end), avgworktime = ((m.completed * m.avgworktime) + (d.completed * d.avgworktime)) / (m.completed + d.completed), maxworktime = (case when d.maxworktime > m.maxworktime then d.maxworktime else m.maxworktime end), minretries = (case when d.minretries < m.minretries then d.minretries else m.minretries end), avgretries = ((m.completed * m.avgretries) + (d.completed * d.avgretries)) / (m.completed + d.retried), maxretries = (case when d.maxretries > m.maxretries then d.maxretries else m.maxretries end) from BPMIProductivityMonthly m inner join @DailyProductivity d on m.queueident = d.queueident where m.reportyear = DATEPART(YEAR, @ReportDate) and m.reportmonth = DATEPART(MONTH, @ReportDate); insert into BPMIProductivityMonthly select DATEPART(YEAR, @ReportDate), DATEPART(MONTH, @ReportDate), d.* from @DailyProductivity d left join BPMIProductivityMonthly m on d.queueident = m.queueident and m.reportyear = DATEPART(YEAR, @ReportDate) and m.reportmonth = DATEPART(MONTH, @ReportDate) where m.reportyear is null; delete from BPMIProductivityDaily where reportdate < DATEADD(DAY, -@DaysToKeep, @ReportDate); delete from BPMIProductivityMonthly where reportyear <= DATEPART(YEAR, (DATEADD(MONTH, -@MonthsToKeep, @ReportDate))) and reportmonth < DATEPART(MONTH, (DATEADD(MONTH, -@MonthsToKeep, @ReportDate))); delete from BPMIProductivityShadow where eventdatetime < @ReportDate; return; ')exec('')exec('alter procedure usp_RefreshUtilisationData @ReportDate datetime, @DaysToKeep int, @MonthsToKeep int as declare @ReportTo datetime; declare @DailyUtilisation table ( resourceid uniqueidentifier, processid uniqueidentifier, h0 int, h1 int, h2 int, h3 int, h4 int, h5 int, h6 int, h7 int, h8 int, h9 int, h10 int, h11 int, h12 int, h13 int, h14 int, h15 int, h16 int, h17 int, h18 int, h19 int, h20 int, h21 int, h22 int, h23 int); set @ReportTo = DATEADD(DAY, 1, @ReportDate); with hours5 as ( select 0 as h union all select 0 union all select 0 union all select 0 union all select 0), hours25 as ( select ROW_NUMBER() over(order by a.h) - 1 as h from hours5 a cross join hours5 b) insert into @DailyUtilisation select resourceid, processid, [0],[1],[2],[3],[4],[5], [6],[7],[8],[9],[10],[11], [12],[13],[14],[15],[16],[17], [18],[19],[20],[21],[22],[23] from( select tp.resourceid, tp.processid, [Hour], case when tp.startdatetime < intervals.StartDate then case when ISNULL(tp.enddatetime, @ReportTo) > intervals.EndDate then DATEDIFF(SECOND, intervals.StartDate, intervals.EndDate) when ISNULL(tp.enddatetime, @ReportTo) between intervals.StartDate and intervals.EndDate then DATEDIFF(SECOND, intervals.StartDate, ISNULL(tp.enddatetime, @ReportTo)) else 0 end when tp.startdatetime between intervals.StartDate and intervals.EndDate then case when ISNULL(tp.enddatetime, @ReportTo) > intervals.EndDate then DATEDIFF(SECOND, intervals.StartDate, intervals.EndDate) else DATEDIFF(SECOND, tp.startdatetime, ISNULL(tp.enddatetime, @ReportTo)) end else 0 end as Duration from BPMIUtilisationShadow tp inner join hours25 hrs on hrs.h between 0 and 23 cross apply ( select hrs.h as [Hour], DATEADD(HOUR, hrs.h, @ReportDate) as StartDate, DATEADD(HOUR, hrs.h + 1, @ReportDate) as EndDate) as intervals ) as src pivot (SUM(Duration) for [Hour] in ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23])) as piv; insert into BPMIUtilisationDaily select @ReportDate, * from @DailyUtilisation; update BPMIUtilisationMonthly set hr0 = hr0 + d.h0, hr1 = hr1 + d.h1, hr2 = hr2 + d.h2, hr3 = hr3 + d.h3, hr4 = hr4 + d.h4, hr5 = hr5 + d.h5, hr6 = hr6 + d.h6, hr7 = hr7 + d.h7, hr8 = hr8 + d.h8, hr9 = hr9 + d.h9, hr10 = hr10 + d.h10, hr11 = hr11 + d.h11, hr12 = hr12 + d.h12, hr13 = hr13 + d.h13, hr14 = hr14 + d.h14, hr15 = hr15 + d.h15, hr16 = hr16 + d.h16, hr17 = hr17+d.h17, hr18 = hr18+d.h18, hr19 = hr19 + d.h19, hr20 = hr20 + d.h20, hr21 = hr21 + d.h21, hr22 = hr22 + d.h22, hr23 = hr23 + d.h23 from BPMIUtilisationMonthly m inner join @DailyUtilisation d on m.resourceid = d.resourceid and m.processid = d.processid where m.reportyear = DATEPART(YEAR, @ReportDate) and m.reportmonth = DATEPART(MONTH, @ReportDate); insert into BPMIUtilisationMonthly select DATEPART(YEAR, @ReportDate), DATEPART(MONTH, @ReportDate), d.* from @DailyUtilisation d left join BPMIUtilisationMonthly m on d.resourceid = m.resourceid and d.processid = m.processid and m.reportyear = DATEPART(YEAR, @ReportDate) and m.reportmonth = DATEPART(MONTH, @ReportDate) where m.reportyear is null; delete from BPMIUtilisationDaily where reportdate < DATEADD(DAY, -@DaysToKeep, @ReportDate); delete from BPMIUtilisationMonthly where reportyear <= DATEPART(YEAR, (DATEADD(MONTH, -@MonthsToKeep, @ReportDate))) and reportmonth < DATEPART(MONTH, (DATEADD(MONTH, -@MonthsToKeep, @ReportDate))); delete from BPMIUtilisationShadow where enddatetime is not null and enddatetime < @ReportDate; return; ')exec('')exec('alter procedure usp_RefreshMI as declare @Today datetime, @LastRefresh datetime, @ReportDate datetime, @DaysToKeep int, @MonthsToKeep int, @MIEnabled bit; select @MIEnabled=mienabled, @DaysToKeep=dailyfor, @MonthsToKeep=monthlyfor, @LastRefresh=lastrefresh from BPAMIControl where id=1; if @MIEnabled=0 return; set @Today=CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); if @LastRefresh is null set @ReportDate=CAST(FLOOR(CAST(DATEADD(DAY, -1, @Today) as float)) as datetime); else set @ReportDate=CAST(FLOOR(CAST(DATEADD(DAY, 1, @LastRefresh) as float)) as datetime); update BPAMIControl set refreshinprogress=1 where id=1 and refreshinprogress=0; if @@ROWCOUNT <> 1 return; begin try while @ReportDate<@Today begin begin transaction; exec usp_RefreshUtilisationData @ReportDate, @DaysToKeep, @MonthsToKeep; exec usp_RefreshProductivityData @ReportDate, @DaysToKeep, @MonthsToKeep; update BPAMIControl set lastrefresh=@ReportDate where id=1; commit; set @ReportDate=DATEADD(DAY, 1, @ReportDate); end end try begin catch rollback; declare @ErrMsg nvarchar(4000), @ErrSeverity int select @ErrMsg=ERROR_MESSAGE(), @ErrSeverity=ERROR_SEVERITY() raiserror(@ErrMsg, @ErrSeverity, 1) end catch update BPAMIControl set refreshinprogress=0 where id=1; return; ')exec('')exec('alter procedure BPDS_WorkforceAvailability as select ''Percentage'' as Label, CAST((CAST(r.ready as decimal)/r.total)*100 as decimal(6,2)) as "% Available" from (select SUM(case when [status] = ''Ready'' then 1 else 0 end) as ready, COUNT(*) as total from BPAResource where (AttributeID & 13) = 0) as r; return; ')exec('')exec('alter procedure BPDS_TotalAutomations as select case when ProcessType = ''O'' then ''Objects'' else ''Processes'' end as [Type], COUNT(*) as Total from BPAProcess where ProcessType in (''O'', ''P'') group by ProcessType; return; ')exec('')exec('alter procedure BPDS_LargestTables @NumberOfTables int = 5 as select top(@NumberOfTables) t.name as "Table Name", CAST(CAST((SUM(a.total_pages)*8) as decimal)/1024 as decimal(12,2)) as "Size (Mb)" from sys.tables t inner join sys.indexes i on t.object_id = i.object_id inner join sys.partitions p on i.object_id = p.object_id and i.index_id = p.index_id inner join sys.allocation_units a on p.partition_id = a.container_id where t.name like ''BP%'' and i.object_id > 255 and i.index_id <= 1 group by t.name order by SUM(a.total_pages) desc; return; ')exec('')exec('alter procedure BPDS_DailyUtilisation @BPResourceName nvarchar(max) = null, @NumberOfDays int = 7, @DisplayUnits nvarchar(max) = ''minute'' as declare @Today datetime; set @Today = CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); select DATENAME(day, u.reportdate) + ''-'' + DATENAME(month, u.reportdate) as "Day", case when @DisplayUnits = ''second'' then CAST(Total as decimal(12,2)) when @DisplayUnits = ''hour'' then CAST(Total/3600 as decimal(12,2)) when @DisplayUnits = ''percentage'' then CAST(Total/(Resources*86400/100) as decimal(12,2)) else CAST(Total/60 as decimal(12,2)) end as "Total" from ( select d.reportdate, CAST(SUM(d.hr0 + d.hr1 + d.hr2 + d.hr3 + d.hr4 + d.hr5 + d.hr6 + d.hr7 + d.hr8 + d.hr9 + d.hr10 + d.hr11 + d.hr12 + d.hr13 + d.hr14 + d.hr15 + d.hr16 + d.hr17 + d.hr18 + d.hr19 + d.hr20 + d.hr21 + d.hr22 + d.hr23) as float) as "Total", COUNT(distinct(r.resourceid)) as "Resources" from BPMIUtilisationDaily d inner join BPAResource r on d.resourceid = r.resourceid where d.reportdate >= DATEADD(day, -@NumberOfDays, @Today) and (@BPResourceName is null or @BPResourceName = r.name) group by d.reportdate ) as u; return; ')exec('')exec('alter procedure BPDS_ProcessUtilisationByHour @BPProcessName nvarchar(max) = null, @DisplayUnits nvarchar(max) = ''minute'' as declare @Today datetime; set @Today = CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); declare @Units int; select @Units = case when @DisplayUnits = ''second'' then 1 when @DisplayUnits = ''hour'' then 3600 else 60 end; select ProcessName, case when @DisplayUnits = ''percentage'' then CAST(Interval1/(Resources*7200/100) as decimal(12,2)) else CAST(Interval1/@Units as decimal(12,2)) end as "00:00", case when @DisplayUnits = ''percentage'' then CAST(Interval2/(Resources*7200/100) as decimal(12,2)) else CAST(Interval2/@Units as decimal(12,2)) end as "02:00", case when @DisplayUnits = ''percentage'' then CAST(Interval3/(Resources*7200/100) as decimal(12,2)) else CAST(Interval3/@Units as decimal(12,2)) end as "04:00", case when @DisplayUnits = ''percentage'' then CAST(Interval4/(Resources*7200/100) as decimal(12,2)) else CAST(Interval4/@Units as decimal(12,2)) end as "06:00", case when @DisplayUnits = ''percentage'' then CAST(Interval5/(Resources*7200/100) as decimal(12,2)) else CAST(Interval5/@Units as decimal(12,2)) end as "08:00", case when @DisplayUnits = ''percentage'' then CAST(Interval6/(Resources*7200/100) as decimal(12,2)) else CAST(Interval6/@Units as decimal(12,2)) end as "10:00", case when @DisplayUnits = ''percentage'' then CAST(Interval7/(Resources*7200/100) as decimal(12,2)) else CAST(Interval7/@Units as decimal(12,2)) end as "12:00", case when @DisplayUnits = ''percentage'' then CAST(Interval8/(Resources*7200/100) as decimal(12,2)) else CAST(Interval8/@Units as decimal(12,2)) end as "14:00", case when @DisplayUnits = ''percentage'' then CAST(Interval9/(Resources*7200/100) as decimal(12,2)) else CAST(Interval9/@Units as decimal(12,2)) end as "16:00", case when @DisplayUnits = ''percentage'' then CAST(Interval10/(Resources*7200/100) as decimal(12,2)) else CAST(Interval10/@Units as decimal(12,2)) end as "18:00", case when @DisplayUnits = ''percentage'' then CAST(Interval11/(Resources*7200/100) as decimal(12,2)) else CAST(Interval11/@Units as decimal(12,2)) end as "20:00", case when @DisplayUnits = ''percentage'' then CAST(Interval12/(Resources*7200/100) as decimal(12,2)) else CAST(Interval12/@Units as decimal(12,2)) end as "22:00" from ( select p.name as ProcessName, CAST(CAST(SUM(d.hr0 + d.hr1) as decimal) as decimal(12,2)) as "Interval1", CAST(CAST(SUM(d.hr2 + d.hr3) as decimal) as decimal(12,2)) as "Interval2", CAST(CAST(SUM(d.hr4 + d.hr5) as decimal) as decimal(12,2)) as "Interval3", CAST(CAST(SUM(d.hr6 + d.hr7) as decimal) as decimal(12,2)) as "Interval4", CAST(CAST(SUM(d.hr8 + d.hr9) as decimal) as decimal(12,2)) as "Interval5", CAST(CAST(SUM(d.hr10 + d.hr11) as decimal) as decimal(12,2)) as "Interval6", CAST(CAST(SUM(d.hr12 + d.hr13) as decimal) as decimal(12,2)) as "Interval7", CAST(CAST(SUM(d.hr14 + d.hr15) as decimal) as decimal(12,2)) as "Interval8", CAST(CAST(SUM(d.hr16 + d.hr17) as decimal) as decimal(12,2)) as "Interval9", CAST(CAST(SUM(d.hr18 + d.hr19) as decimal) as decimal(12,2)) as "Interval10", CAST(CAST(SUM(d.hr20 + d.hr21) as decimal) as decimal(12,2)) as "Interval11", CAST(CAST(SUM(d.hr22 + d.hr23) as decimal) as decimal(12,2)) as "Interval12", COUNT(distinct(d.resourceid)) as "Resources" from BPMIUtilisationDaily d inner join BPAProcess p on d.processid = p.processid where d.reportdate = DATEADD(day, -1, @Today) and (@BPProcessName is null or @BPProcessName = p.name) group by p.name ) as u; return; ')exec('')exec('alter procedure BPDS_ResourceUtilisationByHour @BPResourceName nvarchar(max) = null, @DisplayUnits nvarchar(max) = ''minute'' as declare @Today datetime; set @Today = CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); declare @Units decimal; select @Units = case when @DisplayUnits = ''second'' then 1 when @DisplayUnits = ''hour'' then 3600 else 60 end; select ''Utilisation'', case when @DisplayUnits = ''percentage'' then CAST(Interval1/(Resources*7200/100) as decimal(12,2)) else CAST(Interval1/@Units as decimal(12,2)) end as "00:00", case when @DisplayUnits = ''percentage'' then CAST(Interval2/(Resources*7200/100) as decimal(12,2)) else CAST(Interval2/@Units as decimal(12,2)) end as "02:00", case when @DisplayUnits = ''percentage'' then CAST(Interval3/(Resources*7200/100) as decimal(12,2)) else CAST(Interval3/@Units as decimal(12,2)) end as "04:00", case when @DisplayUnits = ''percentage'' then CAST(Interval4/(Resources*7200/100) as decimal(12,2)) else CAST(Interval4/@Units as decimal(12,2)) end as "06:00", case when @DisplayUnits = ''percentage'' then CAST(Interval5/(Resources*7200/100) as decimal(12,2)) else CAST(Interval5/@Units as decimal(12,2)) end as "08:00", case when @DisplayUnits = ''percentage'' then CAST(Interval6/(Resources*7200/100) as decimal(12,2)) else CAST(Interval6/@Units as decimal(12,2)) end as "10:00", case when @DisplayUnits = ''percentage'' then CAST(Interval7/(Resources*7200/100) as decimal(12,2)) else CAST(Interval7/@Units as decimal(12,2)) end as "12:00", case when @DisplayUnits = ''percentage'' then CAST(Interval8/(Resources*7200/100) as decimal(12,2)) else CAST(Interval8/@Units as decimal(12,2)) end as "14:00", case when @DisplayUnits = ''percentage'' then CAST(Interval9/(Resources*7200/100) as decimal(12,2)) else CAST(Interval9/@Units as decimal(12,2)) end as "16:00", case when @DisplayUnits = ''percentage'' then CAST(Interval10/(Resources*7200/100) as decimal(12,2)) else CAST(Interval10/@Units as decimal(12,2)) end as "18:00", case when @DisplayUnits = ''percentage'' then CAST(Interval11/(Resources*7200/100) as decimal(12,2)) else CAST(Interval11/@Units as decimal(12,2)) end as "20:00", case when @DisplayUnits = ''percentage'' then CAST(Interval12/(Resources*7200/100) as decimal(12,2)) else CAST(Interval12/@Units as decimal(12,2)) end as "22:00" from ( select CAST(CAST(SUM(d.hr0 + d.hr1) as decimal) as decimal(12,2)) as "Interval1", CAST(CAST(SUM(d.hr2 + d.hr3) as decimal) as decimal(12,2)) as "Interval2", CAST(CAST(SUM(d.hr4 + d.hr5) as decimal) as decimal(12,2)) as "Interval3", CAST(CAST(SUM(d.hr6 + d.hr7) as decimal) as decimal(12,2)) as "Interval4", CAST(CAST(SUM(d.hr8 + d.hr9) as decimal) as decimal(12,2)) as "Interval5", CAST(CAST(SUM(d.hr10 + d.hr11) as decimal) as decimal(12,2)) as "Interval6", CAST(CAST(SUM(d.hr12 + d.hr13) as decimal) as decimal(12,2)) as "Interval7", CAST(CAST(SUM(d.hr14 + d.hr15) as decimal) as decimal(12,2)) as "Interval8", CAST(CAST(SUM(d.hr16 + d.hr17) as decimal) as decimal(12,2)) as "Interval9", CAST(CAST(SUM(d.hr18 + d.hr19) as decimal) as decimal(12,2)) as "Interval10", CAST(CAST(SUM(d.hr20 + d.hr21) as decimal) as decimal(12,2)) as "Interval11", CAST(CAST(SUM(d.hr22 + d.hr23) as decimal) as decimal(12,2)) as "Interval12", COUNT(distinct(r.resourceid)) as "Resources" from BPMIUtilisationDaily d inner join BPAResource r on d.resourceid = r.resourceid where d.reportdate = DATEADD(day, -1, @Today) and (@BPResourceName is null or @BPResourceName = r.name) ) as u; return; ')exec('')exec('alter procedure BPDS_AverageHandlingTime @BPQueueName nvarchar(max) = null, @NumberOfDays int = 7 as declare @Today datetime; set @Today = CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); select q.name, CAST(AVG(d.avgworktime) as decimal(12,2)) as "Average Time" from BPMIProductivityDaily d inner join BPAWorkQueue q on d.queueident = q.ident where d.reportdate > DATEADD(day, -@NumberOfDays, @Today) group by q.name; return; ')exec('')exec('alter procedure BPDS_DailyProductivity @BPQueueName nvarchar(max) = null, @NumberOfDays int = 7 as declare @Today datetime; set @Today = CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); select d.reportdate, SUM(d.created) as New, SUM(d.deferred) as Deferred, SUM(d.completed) as Complete, SUM(d.retried) as Retries, SUM(d.exceptioned) as Exceptions from BPMIProductivityDaily d inner join BPAWorkQueue q on d.queueident = q.ident where d.reportdate > DATEADD(day, -@NumberOfDays, @Today) and (@BPQueueName is null or @BPQueueName = q.name) group by d.reportdate; return; ')exec('')exec('alter procedure BPDS_FTEProductivityComparison @BPQueueName nvarchar(max) = null, @NumberOfMonths int = 6, @FTEProductivity decimal(12,2) = 0, @FTECost decimal(12,2) = 0, @DisplayAs nvarchar(max) = ''percentage'' as declare @FromYear int, @FromMonth int; set @FromYear = DATEPART(YEAR, (DATEADD(MONTH, -@NumberOfMonths, GETUTCDATE()))); set @FromMonth = DATEPART(MONTH, (DATEADD(MONTH, -@NumberOfMonths, GETUTCDATE()))); declare @Today datetime; set @Today = CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); select TheDate, case when @FTEProductivity <> 0 then case when @DisplayAs = ''cost'' then CAST((completed/(@FTEProductivity*DaysInMonth))*@FTECost as decimal(12,2)) when @DisplayAs = ''number'' then CAST(completed/(@FTEProductivity*DaysInMonth) as decimal(12,2)) else CAST((completed/(@FTEProductivity*DaysInMonth))*100 as decimal(12,2)) end else completed end from ( select DATENAME(month, DATEADD(month, reportmonth, -1)) + '' '' + CAST(reportyear as nvarchar(4)) as TheDate, DAY(DATEADD(day, -1, DATEADD(month, 1, CAST(CAST(reportyear as nvarchar) + ''-'' + CAST(reportmonth as nvarchar) + ''-1'' as datetime)))) as DaysInMonth, SUM(completed) as Completed from BPMIProductivityMonthly m inner join BPAWorkQueue q on m.queueident = q.ident where m.reportyear >= @FromYear and m.reportmonth > @FromMonth and (@BPQueueName is null or @BPQueueName = q.name) group by reportmonth, reportyear ) as p return; ')exec('')exec('alter procedure BPDS_AverageRetries @BPQueueName nvarchar(max) = null, @NumberOfDays int = 7 as declare @Today datetime; set @Today = CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); select q.name, CAST(AVG(d.avgretries) as decimal(12,2)) as "Retries" from BPMIProductivityDaily d inner join BPAWorkQueue q on d.queueident = q.ident where d.reportdate > DATEADD(day, -@NumberOfDays, @Today) group by q.name; return; ')exec('')exec('alter procedure BPDS_Exceptions @BPQueueName nvarchar(max) = null as declare @Today datetime; set @Today = CAST(FLOOR(CAST(GETUTCDATE() as float)) as datetime); declare @ColumnName nvarchar(max); declare @Query nvarchar(max); declare @WhereClause nvarchar(max); if @BPQueueName is not null set @WhereClause = '' and q.name = '''''' + @BPQueueName + ''''''''; with dates as ( select DATEADD(day, -1, @Today) as TheDate union select DATEADD(day, -2, @Today) as TheDate union select DATEADD(day, -3, @Today) as TheDate) select @ColumnName = ISNULL(@ColumnName + '','', '''') + QUOTENAME(CONVERT(nvarchar(10), TheDate, 1)) from dates; set @Query = ''select name, '' + @ColumnName + '' from (select q.name, convert(nvarchar(10), d.reportdate, 1) as pivotdate, d.exceptioned from BPMIProductivityDaily d inner join BPAWorkQueue q on d.queueident = q.ident where d.reportdate > DATEADD(day, -3, '' + CONVERT(nvarchar(10), @Today, 101) + '') '' + ISNULL(@WhereClause, '''') + '') as src pivot (sum(exceptioned) for pivotdate in ('' + @ColumnName + '')) as pvt'' exec(@Query) return; ')exec('')exec('delete from BPATile; insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Workforce Availability'',0,''Percentage of registered resources available for work'',0,''<Chart type="8" plotByRow="false"><Procedure name="BPDS_WorkforceAvailability" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Largest Database Tables'',0,''The largest five tables in the database (Mb)'',0,''<Chart type="6" plotByRow="false"><Procedure name="BPDS_LargestTables" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Total Automations'',0,''Number of Objects and Processes in the database'',0,''<Chart type="6" plotByRow="false"><Procedure name="BPDS_TotalAutomations" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Daily Utilisation Summary'',0,''Overall resource utilisation over last 7 days'',0,''<Chart type="3" plotByRow="false"><Procedure name="BPDS_DailyUtilisation" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Process Utilisation Yesterday'',0,''Overall time spent running each process'',0,''<Chart type="4" plotByRow="true"><Procedure name="BPDS_ProcessUtilisationByHour" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Resource Utilisation Yesterday'',0,''Overall time spent running sessions'',0,''<Chart type="3" plotByRow="true"><Procedure name="BPDS_ResourceUtilisationByHour" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Daily Productivity'',0,''Number of new/deferred/completed cases in last 7 days'',0,''<Chart type="3" plotByRow="false"><Procedure name="BPDS_DailyProductivity" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Average Handling Time'',0,''Average work time for completed cases by queue'',0,''<Chart type="0" plotByRow="false"><Procedure name="BPDS_AverageHandlingTime" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''FTE Comparison'',0,''Productivity in comparison to a human FTE'',0,''<Chart type="3" plotByRow="false"><Procedure name="BPDS_FTEProductivityComparison" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Average Retries'',0,''Average number of retries for completed cases by queue'',0,''<Chart type="6" plotByRow="false"><Procedure name="BPDS_AverageRetries" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Exceptions'',0,''Number of exceptions by queue'',0,''<Chart type="3" plotByRow="false"><Procedure name="BPDS_Exceptions" /></Chart>''); delete from BPADashboard; insert into BPADashboard (id, name, dashtype, userid) values(''00000000-0000-0000-0000-000000000000'', ''Default dashboard'', 0, null); insert into BPADashboardTile (dashid, tileid, displayorder, width, height) select ''00000000-0000-0000-0000-000000000000'', t.id, ROW_NUMBER() over (order by t.id), 1, 1 from BPATile t where t.name in (''Workforce Availability''); INSERT INTO BPADBVersion VALUES ( ''179'', GETUTCDATE(), ''db_upgradeR179.sql UTC'', ''Adds new tables and stored procedures for MI reporting'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='180') begin exec('insert into BPAPerm (name) values(''Edit Process Groups''); insert into BPAPerm (name) values(''Edit Object Groups''); insert into BPAPermGroupMember (permgroupid, permid) select pg.id, p.id from BPAPermGroup pg cross join BPAPerm p where pg.name = ''Process Studio'' and p.name = ''Edit Process Groups''; insert into BPAPermGroupMember (permgroupid, permid) select pg.id, p.id from BPAPermGroup pg cross join BPAPerm p where pg.name = ''Object Studio'' and p.name = ''Edit Object Groups''; insert into BPAUserRolePerm (userroleid, permid) select r.id, p.id from BPAUserRole r cross join BPAPerm p where r.name in (''Developer'', ''Process Administrator'', ''System Administrator'') and p.name in (''Edit Process Groups'', ''Edit Object Groups''); create table BPAGroupGroup ( groupid uniqueidentifier not null constraint FK_BPAGroupGroup_BPAGroup_groupid foreign key references BPAGroup(id) on delete cascade, memberid uniqueidentifier not null constraint FK_BPAGroupGroup_BPAGroup_memberid foreign key references BPAGroup(id) constraint UNQ_BPAGroupGroup_memberid unique, constraint PK_BPAGroupGroup primary key clustered (groupid, memberid) ); insert into BPAGroupGroup (groupid, memberid) select g.parentid, g.id from BPAGroup g where g.parentid is not null; alter table BPAGroup drop constraint FK_BPAGroup_BPAGroup; alter table BPAGroup drop column parentid; create table BPATree ( id int not null primary key, name nvarchar(255) not null ); insert into BPATree (id, name) select 1, ''Tiles'' union all select 2, ''Processes'' union all select 3, ''Objects'' union all select 4, ''Queues'' union all select 5, ''Resources''; update BPAGroup set treeid = 2 where treeid = 0; alter table BPAGroup add constraint FK_BPAGroup_BPATree foreign key (treeid) references BPATree(id); ')exec('')exec('declare @treeid int; select @treeid = id from BPATree where name = ''Processes''; insert into BPAGroup (treeid, id, name) select @treeid, pg.GroupID, pg.GroupName from BPAProcessGroup pg; insert into BPAGroupProcess (groupid, processid) select gm.GroupID, gm.ProcessID from BPAProcessGroupMembership gm; alter table BPAPackageProcessGroupMember drop constraint FK_BPAPackageProcessGroup_BPAProcessGroupMembership; alter table BPAPackageProcessGroupMember add constraint FK_BPAPackageProcessGroup_BPAGroupProcess foreign key (processgroupid, processid) references BPAGroupProcess(groupid, processid) on delete cascade; drop table BPAProcessGroupMembership; drop table BPAProcessGroup; create table BPAGroupResource ( groupid uniqueidentifier not null constraint FK_BPAGroupResource_BPAGroup foreign key references BPAGroup(id) on delete cascade, memberid uniqueidentifier not null constraint FK_BPAGroupResource_BPAResource foreign key references BPAResource(resourceid) on delete cascade, constraint PK_BPAGroupResource primary key clustered (groupid, memberid) ); create table BPAGroupQueue ( groupid uniqueidentifier not null constraint FK_BPAGroupQueue_BPAGroup foreign key references BPAGroup(id) on delete cascade, memberid int not null constraint FK_BPAGroupQueue_BPAWorkQueue foreign key references BPAWorkQueue(ident) on delete cascade, constraint PK_BPAGroupQueue primary key clustered (groupid, memberid) ); ')exec('')exec('if not exists(select * from sys.views where name = ''BPVGroupedTiles'') exec (N''create view BPVGroupedTiles as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedProcessesObjects'') exec (N''create view BPVGroupedProcessesObjects as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedProcesses'') exec (N''create view BPVGroupedProcesses as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedObjects'') exec (N''create view BPVGroupedObjects as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedResources'') exec (N''create view BPVGroupedResources as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedQueues'') exec (N''create view BPVGroupedQueues as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedGroups'') exec (N''create view BPVGroupedGroups as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedActiveProcesses'') exec (N''create view BPVGroupedActiveProcesses as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedActiveObjects'') exec (N''create view BPVGroupedActiveObjects as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupedPublishedProcesses'') exec (N''create view BPVGroupedPublishedProcesses as select 1 as placeholder''); if not exists(select * from sys.views where name = ''BPVGroupTree'') exec (N''create view BPVGroupTree as select 1 as placeholder''); ')exec('')exec('alter view BPVGroupedTiles as select g.treeid as treeid, g.id as groupid, g.name as groupname, t.id as id, t.name as name, t.tiletype as tiletype, t.description as description from BPATile t left join ( BPAGroupTile gt inner join BPAGroup g on gt.groupid = g.id ) on gt.tileid = t.id; ')exec('')exec('alter view BPVGroupedProcessesObjects as select g.treeid as treeid, g.id as groupid, g.name as groupname, p.processid as id, p.name as name, p.ProcessType as processtype, p.description as description, p.createdate as createddate, cu.username as createdby, p.lastmodifieddate as lastmodifieddate, p.attributeid as attributes, mu.username as lastmodifiedby from BPAProcess p join BPAUser cu on p.createdby = cu.userid join BPAUser mu on p.lastmodifiedby = mu.userid left join ( BPAGroupProcess gp inner join BPAGroup g on gp.groupid = g.id ) on gp.processid = p.processid; ')exec('')exec('alter view BPVGroupedProcesses as select * from BPVGroupedProcessesObjects where processtype = ''P''; ')exec('')exec('alter view BPVGroupedObjects as select * from BPVGroupedProcessesObjects where processtype = ''O''; ')exec('')exec('alter view BPVGroupedActiveProcesses as select * from BPVGroupedProcesses where (attributes & 1) = 0; ')exec('')exec('alter view BPVGroupedActiveObjects as select * from BPVGroupedObjects where (attributes & 1) = 0; ')exec('')exec('alter view BPVGroupedPublishedProcesses as select * from BPVGroupedActiveProcesses where (attributes & 2) != 0; ')exec('')exec('alter view BPVGroupedResources as select g.treeid as treeid, g.id as groupid, g.name as groupname, r.resourceid as id, r.name as name, r.attributeid as attributes, r.status as status from BPAResource r left join ( BPAGroupResource gr inner join BPAGroup g on gr.groupid = g.id ) on gr.memberid = r.resourceid; ')exec('')exec('if not exists (select 1 from BPADBVersion where dbversion=''193'') exec('' alter view BPVGroupedQueues as select g.treeid as treeid, g.id as groupid, g.name as groupname, q.ident as id, q.name as name, q.id as guid, q.running as running, q.encryptname as encryptname from BPAWorkQueue q left join ( BPAGroupQueue gq inner join BPAGroup g on gq.groupid = g.id ) on gq.memberid = q.ident;''); ')exec('')exec('alter view BPVGroupedGroups as select g.treeid as treeid, g.id as groupid, g.name as groupname, sg.id as id, sg.name as name from BPAGroup g join BPAGroupGroup gg on gg.groupid = g.id join BPAGroup sg on gg.memberid = sg.id; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''180'', GETUTCDATE(), ''db_upgradeR180.sql UTC'', ''Updates groups for easy access and extensibility;'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='181') begin exec('insert into BPAValCheck (checkid, catid, typeid, description, enabled) values (138, 0, 2, ''Data item ''''{0}'''' is not referenced'', 1); insert into BPAValCheck (checkid, catid, typeid, description, enabled) values (139, 0, 2, ''Collection ''''{0}'''' is not referenced'', 1); insert into BPAValCheck (checkid, catid, typeid, description, enabled) values (140, 0, 2, ''Application element ''''{0}'''' is not referenced'', 1); update BPAPermGroup set name=''Dashboard'' where name=''Review''; create table BPAProcessParentDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessParentDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refParentName nvarchar(128) not null, constraint PK_BPAProcessParentDependency primary key (id) ); INSERT INTO BPADBVersion VALUES ( ''181'', GETUTCDATE(), ''db_upgradeR181.sql UTC'', ''Adds additional process validation checks'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='182') begin exec('if exists (select 1 from sysobjects where id = object_id(''bpa_sp_dropdefault'') and type=''P'') begin drop procedure bpa_sp_dropdefault end ')exec('')exec('create procedure bpa_sp_dropdefault @tableName nvarchar(256), @columnName nvarchar(256) as declare @Command nvarchar(max) select @Command = ''ALTER TABLE '' + @tableName + '' drop constraint '' + d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = @tableName and c.name = @columnName; execute (@Command); ')exec('')exec('if exists (select 1 from sysobjects where id = object_id(''bpa_sp_dropunique'') and type=''P'') begin drop procedure bpa_sp_dropunique end ')exec('')exec('create procedure bpa_sp_dropunique @tableName nvarchar(256), @columnName nvarchar(256) as declare @Command nvarchar(1000) select @Command = ''ALTER TABLE '' + @tableName + '' drop constraint '' + d.name from sys.tables t join sys.indexes d on d.object_id = t.object_id join sys.columns c on c.object_id = t.object_id where t.name = @tableName and d.type=2 and d.is_unique=1 and c.name = @columnName; execute (@Command); ')exec('')exec('DROP TABLE BPASession_OLD; DROP TABLE BPASessionLog_OLD EXEC sp_rename ''BPASessionLog'',''BPASessionLog_v4'' EXEC sp_rename ''PK_BPASessionLog'',''PK_BPASessionLog_v4'' EXEC sp_rename ''FK_BPASessionLog_BPASession'', ''FK_BPASessionLog_BPASession_v4'' ')exec('')exec('CREATE TABLE BPASessionLog ( sessionnumber int NOT NULL, seqnum int NOT NULL, stageid uniqueidentifier NULL, stagename nvarchar(128) NULL, stagetype int NULL, processname nvarchar(128) NULL, pagename nvarchar(128) NULL, objectname nvarchar(128) NULL, actionname nvarchar(128) NULL, result nvarchar(max) NULL, resulttype int NULL, startdatetime datetime NULL, enddatetime datetime NULL, attributexml nvarchar(max) NULL, automateworkingset bigint NULL, targetappname nvarchar(32) NULL, targetappworkingset bigint NULL, CONSTRAINT PK_BPASessionLog PRIMARY KEY CLUSTERED ( sessionnumber ASC, seqnum ASC )) ')exec('')exec('ALTER TABLE BPASessionLog WITH CHECK ADD CONSTRAINT FK_BPASessionLog_BPASession FOREIGN KEY(sessionnumber) REFERENCES BPASession (sessionnumber); ')exec('')exec('ALTER TABLE BPASession ALTER COLUMN runningosusername nvarchar(50); ALTER TABLE BPASession ALTER COLUMN startparamsxml nvarchar(max); ALTER TABLE BPASession ALTER COLUMN logginglevelsxml nvarchar(max); ALTER TABLE BPASession ALTER COLUMN sessionstatexml nvarchar(max); ALTER TABLE BPAUser ALTER COLUMN username nvarchar(128); ALTER TABLE BPAUser ALTER COLUMN password nvarchar(100); ALTER TABLE BPAUser ALTER COLUMN useremail nvarchar(60); ALTER TABLE BPAUser ALTER COLUMN preferredStatisticsInterval nvarchar(60); ALTER TABLE BPAUser ALTER COLUMN systemusername nvarchar(128); ALTER TABLE BPAProcess ALTER COLUMN ProcessType nvarchar(1); ALTER TABLE BPAProcess ALTER COLUMN name nvarchar(128); ALTER TABLE BPAProcess ALTER COLUMN description nvarchar(1000); ALTER TABLE BPAProcess ALTER COLUMN version nvarchar(20); ALTER TABLE BPAProcess ALTER COLUMN processxml nvarchar(max); CREATE table BPAProcessEnvVar_new ( processid uniqueidentifier NOT NULL, name nvarchar(64) NOT NULL, CONSTRAINT PK_BPAProcessEnvVar_new PRIMARY KEY CLUSTERED (processid,name) ); INSERT into BPAProcessEnvVar_new (processid, name) select processid, name from BPAProcessEnvVar; drop table BPAProcessEnvVar; exec sp_rename ''BPAProcessEnvVar_new'', ''BPAProcessEnvVar''; exec sp_rename ''PK_BPAProcessEnvVar_new'', ''PK_BPAProcessEnvVar''; ')exec('')exec('ALTER TABLE BPAProcessBackUp ALTER COLUMN processxml nvarchar(max); ALTER TABLE BPAStatus ALTER COLUMN type nvarchar(10); ALTER TABLE BPAStatus ALTER COLUMN description nvarchar(20); ALTER TABLE BPAResource DROP CONSTRAINT UNQ_BPAResource_name; ALTER TABLE BPAResource ALTER COLUMN name nvarchar(128); ALTER TABLE BPAResource ALTER COLUMN status nvarchar(10); ALTER TABLE BPAResource ADD CONSTRAINT UNQ_BPAResource_name unique (name); create table BPAEnvLock_new ( name nvarchar(255) not null constraint PK_BPAEnvLock_new primary key, token nvarchar(255) null, sessionid uniqueidentifier null constraint FK_BPAEnvLock_BPASession_new foreign key references BPASession(sessionid), locktime datetime null, comments nvarchar(1024) null ); insert into BPAEnvLock_new (name, token, sessionid, locktime, comments) select name, token, sessionid, locktime, comments from BPAEnvLock; drop table BPAEnvLock; exec sp_rename ''BPAEnvLock_new'', ''BPAEnvLock''; exec sp_rename ''PK_BPAEnvLock_new'', ''PK_BPAEnvLock''; exec sp_rename ''FK_BPAEnvLock_BPASession_new'', ''FK_BPAEnvLock_BPASession''; ALTER TABLE BPAScenarioLink ALTER COLUMN scenarioname nvarchar(50); ')exec('')exec('CREATE TABLE BPAToolPosition_new ( UserID uniqueidentifier NULL, Name nvarchar(100) NULL, Position nchar(1) NULL, X int NULL, Y int NULL, Mode nchar(1) NULL, Visible bit NULL ); create clustered index INDEX_BPAToolPosition_userid_name_new on BPAToolPosition_new(UserID, Name); insert into BPAToolPosition_new(UserID, Name, Position, X, Y, Mode, Visible) select UserID, Name, Position, X, Y, Mode, Visible from BPAToolPosition; drop table BPAToolPosition; ')exec('')exec('exec sp_rename ''BPAToolPosition_new'', ''BPAToolPosition''; exec sp_rename ''BPAToolPosition.INDEX_BPAToolPosition_userid_name_new'', ''INDEX_BPAToolPosition_userid_name''; ALTER TABLE BPAScheduleList DROP CONSTRAINT UNQ_BPAScheduleList_listtype_name; ALTER TABLE BPAScheduleList ALTER COLUMN name nvarchar(128); ALTER TABLE BPAScheduleList ALTER COLUMN description nvarchar(max); ALTER TABLE BPAScheduleList ADD CONSTRAINT UNQ_BPAScheduleList_listtype_name unique (listtype, name); ALTER TABLE BPAScenario ALTER COLUMN scenariotext nvarchar(1000); ALTER TABLE BPAScenario ALTER COLUMN scenarionotes nvarchar(1000); CREATE TABLE BPAResourceConfig_new ( name nvarchar(128) NOT NULL, config nvarchar(max) NULL, CONSTRAINT PK_BPAResourceConfig_new PRIMARY KEY CLUSTERED (name ASC) ); insert into BPAResourceConfig_new (name, config) select name, config from BPAResourceConfig; drop table BPAResourceConfig; exec sp_rename ''BPAResourceConfig_new'', ''BPAResourceConfig''; exec sp_rename ''PK_BPAResourceConfig_new'', ''PK_BPAResourceConfig''; ALTER TABLE BPAResourceAttribute ALTER COLUMN AttributeName nvarchar(64); ALTER TABLE BPAReport ALTER COLUMN name nvarchar(128); ALTER TABLE BPAReport ALTER COLUMN description nvarchar(1000); ALTER TABLE BPASchedule ALTER COLUMN name nvarchar(128); ALTER TABLE BPASchedule ALTER COLUMN description nvarchar(max); ALTER TABLE BPASchedule ALTER COLUMN deletedname nvarchar(128); CREATE TABLE BPAAlertsMachines_new ( MachineName nvarchar(128) NOT NULL, CONSTRAINT PK_BPAAlertsMachines_new PRIMARY KEY CLUSTERED (MachineName ASC) ); insert into BPAAlertsMachines_new (MachineName) select MachineName from BPAAlertsMachines; drop table BPAAlertsMachines; exec sp_rename ''BPAAlertsMachines_new'', ''BPAAlertsMachines''; exec sp_rename ''PK_BPAAlertsMachines_new'', ''PK_BPAAlertsMachines''; ALTER TABLE BPAPublicHolidayGroup DROP CONSTRAINT UNQ_BPAPublicHoliday_name; ALTER TABLE BPAPublicHolidayGroup ALTER COLUMN name nvarchar(64); ALTER TABLE BPAPublicHolidayGroup ADD CONSTRAINT UNQ_BPAPublicHoliday_name unique (name); ALTER TABLE BPAPublicHoliday ALTER COLUMN name nvarchar(64); CREATE TABLE BPAProcessMITemplate_new ( templatename nvarchar(32) NOT NULL, processid uniqueidentifier NOT NULL, defaulttemplate bit NOT NULL, templatexml nvarchar(max) NULL ) alter table BPAProcessMITemplate_new add constraint PK_BPAProcessMITemplate_new primary key(templatename, processid); insert into BPAProcessMITemplate_new (templatename, processid, defaulttemplate, templatexml) select templatename, processid, defaulttemplate, templatexml from BPAProcessMITemplate; drop table BPAProcessMITemplate; exec sp_rename ''BPAProcessMITemplate_new'', ''BPAProcessMITemplate''; exec sp_rename ''PK_BPAProcessMITemplate_new'', ''PK_BPAProcessMITemplate''; ALTER TABLE BPAProcessAttribute ALTER COLUMN AttributeName nvarchar(64); ALTER TABLE BPAPasswordRules ALTER COLUMN additional nvarchar(128); ')exec('')exec('ALTER TABLE BPAPackageFont DROP CONSTRAINT FK_BPAPackageFont_BPAFont; CREATE TABLE BPAPackageFont_new ( packageid int NOT NULL, name nvarchar(255) NOT NULL, CONSTRAINT PK_BPAPackageFont_new PRIMARY KEY CLUSTERED (packageid, name) ); CREATE TABLE BPAFont_new ( name nvarchar(255) NOT NULL, version nvarchar(255) NOT NULL, fontdata nvarchar(max) NOT NULL, CONSTRAINT PK_BPAFont_new PRIMARY KEY CLUSTERED (name) ); insert into BPAFont_new (name,version,fontdata) select name,version,fontdata from BPAFont; insert into BPAPackageFont_new (packageid, name) select packageid, name FROM BPAPackageFont; drop table BPAFont; exec sp_rename ''BPAFont_new'', ''BPAFont''; exec sp_rename ''PK_BPAFont_new'', ''PK_BPAFont''; drop table BPAPackageFont; exec sp_rename ''BPAPackageFont_new'', ''BPAPackageFont''; exec sp_rename ''PK_BPAPackageFont_new'', ''PK_BPAPackageFont''; ALTER TABLE BPAPackageFont WITH CHECK ADD CONSTRAINT FK_BPAPackageFont_BPAFont FOREIGN KEY(name) REFERENCES BPAFont (name) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE BPAPackageFont WITH CHECK ADD CONSTRAINT FK_BPAPackageFont_BPAPackage FOREIGN KEY(packageid) REFERENCES BPAPackage (id) ON DELETE CASCADE; exec bpa_sp_dropunique ''BPAExceptionType'', ''type''; ALTER TABLE BPAExceptionType ALTER COLUMN type nvarchar(30); ALTER TABLE BPAExceptionType ADD CONSTRAINT UNQ_BPAExceptionType_type unique (type); ALTER TABLE BPAPackage DROP CONSTRAINT UNQ_BPAPackage_name; ALTER TABLE BPAPackage ALTER COLUMN name nvarchar(255); ALTER TABLE BPAPackage ALTER COLUMN description nvarchar(max); ALTER TABLE BPAPackage ADD CONSTRAINT UNQ_BPAPackage_name unique (name); ')exec('')exec('if exists (select 1 from BPADBVersion where dbversion=''193'') exec('' CREATE TABLE BPACredentials_new ( id uniqueidentifier NOT NULL, name nvarchar(64) NOT NULL, description nvarchar(max) NOT NULL, login nvarchar(64) NOT NULL, password nvarchar(max) NOT NULL, expirydate datetime NULL, invalid bit NULL, encryptid int NULL constraint FK_BPACredentials_BPAKeyStore_new foreign key references BPAKeyStore (id), CONSTRAINT PK_BPACredentials_new PRIMARY KEY CLUSTERED (id ASC) ); insert into BPACredentials_new (id, name, description, login, password, expirydate, invalid, encryptid) select id, name, description, login, password, expirydate, invalid, encryptid from BPACredentials;''); else exec('' CREATE TABLE BPACredentials_new ( id uniqueidentifier NOT NULL, name nvarchar(64) NOT NULL, description nvarchar(max) NOT NULL, login nvarchar(64) NOT NULL, password nvarchar(max) NOT NULL, expirydate datetime NULL, invalid bit NULL, CONSTRAINT PK_BPACredentials_new PRIMARY KEY CLUSTERED (id ASC) ); insert into BPACredentials_new (id, name, description, login, password, expirydate, invalid) select id, name, description, login, password, expirydate, invalid from BPACredentials;''); ALTER TABLE BPACredentialRole DROP CONSTRAINT FK_BPACredentialRole_BPACredential; ALTER TABLE BPAPackageCredential DROP CONSTRAINT FK_BPAPackageCredential_BPACredentials; ALTER TABLE BPACredentialsProcesses DROP CONSTRAINT FK_BPACredentialsProcesses_cred; ALTER TABLE BPACredentialsResources DROP CONSTRAINT FK_BPACredentialsResources_cred; ALTER TABLE BPACredentialsProperties DROP CONSTRAINT FK_BPACredentialsProperties_cred; drop table BPACredentials; exec sp_rename ''BPACredentials_new'', ''BPACredentials''; exec sp_rename ''PK_BPACredentials_new'', ''PK_BPACredentials''; if exists (select 1 from BPADBVersion where dbversion=''193'') exec sp_rename ''FK_BPACredentials_BPAKeyStore_new'', ''FK_BPACredentials_BPAKeyStore''; ALTER TABLE BPACredentialsProcesses ADD CONSTRAINT FK_BPACredentials_RoleID FOREIGN KEY (credentialid) REFERENCES BPACredentials (id); ALTER TABLE BPACredentialsResources ADD CONSTRAINT FK_BPACredentialsResources_cred FOREIGN KEY (credentialid) REFERENCES BPACredentials (id); ALTER TABLE BPACredentialsProperties ADD CONSTRAINT FK_BPACredentialsProperties_cred FOREIGN KEY (credentialid) REFERENCES BPACredentials (id); ALTER TABLE BPAPackageCredential ADD CONSTRAINT FK_BPAPackageCredential_BPACredentials FOREIGN KEY (credentialid) REFERENCES BPACredentials(id) on delete cascade; ALTER TABLE BPACredentialRole ADD CONSTRAINT FK_BPACredentialRole_BPACredential FOREIGN KEY (credentialid) REFERENCES BPACredentials (id) on delete cascade; ALTER TABLE BPAAuditEvents ALTER COLUMN sCode nvarchar(10); ALTER TABLE BPAAuditEvents ALTER COLUMN sNarrative nvarchar(500); ALTER TABLE BPAAuditEvents ALTER COLUMN comments nvarchar(512); ALTER TABLE BPAAuditEvents ALTER COLUMN EditSummary nvarchar(max); ALTER TABLE BPAAuditEvents ALTER COLUMN oldXML nvarchar(max); ALTER TABLE BPAAuditEvents ALTER COLUMN newXML nvarchar(max); ALTER TABLE BPAPackageEnvironmentVar DROP CONSTRAINT FK_BPAPackageEnvironmentVar_BPAEnvironmentVar; CREATE TABLE BPAEnvironmentVar_new ( name nvarchar(64) NOT NULL, datatype nvarchar(16) NOT NULL, value nvarchar(max) NOT NULL, description nvarchar(max) NOT NULL, CONSTRAINT PK_BPAEnvironmentVar_new PRIMARY KEY CLUSTERED (name) ); insert into BPAEnvironmentVar_new (name, datatype, value, description) select name, datatype, value, description from BPAEnvironmentVar; CREATE TABLE BPAPackageEnvironmentVar_new ( packageid int NOT NULL, name nvarchar(64) NOT NULL, CONSTRAINT PK_BPAPackageEnvironmentVar_new PRIMARY KEY CLUSTERED (packageid, name) ); insert into BPAPackageEnvironmentVar_new (packageid, name) select packageid, name from BPAPackageEnvironmentVar; drop table BPAEnvironmentVar; exec sp_rename ''BPAEnvironmentVar_new'', ''BPAEnvironmentVar''; exec sp_rename ''PK_BPAEnvironmentVar_new'', ''PK_BPAEnvironmentVar''; drop table BPAPackageEnvironmentVar; exec sp_rename ''BPAPackageEnvironmentVar_new'', ''BPAPackageEnvironmentVar''; exec sp_rename ''PK_BPAPackageEnvironmentVar_new'', ''PK_BPAPackageEnvironmentVar''; ALTER TABLE BPAPackageEnvironmentVar ADD constraint FK_BPAPackageEnvironmentVar_BPAEnvironmentVar FOREIGN KEY (name) references BPAEnvironmentVar(name); ')exec('')exec('CREATE TABLE BPADataTracker_new ( dataname nvarchar(64) not null constraint PK_BPADataTracker_new primary key, versionno bigint not null ); insert into BPADataTracker_new (dataname, versionno) select dataname, versionno from BPADataTracker; drop table BPADataTracker; exec sp_rename ''BPADataTracker_new'', ''BPADataTracker''; exec sp_rename ''PK_BPADataTracker_new'', ''PK_BPADataTracker''; CREATE TABLE [BPAStatistics_new] ( sessionid uniqueidentifier NOT NULL, name nvarchar (50) NOT NULL, datatype nvarchar (32) NULL, value_text nvarchar (255) NULL, value_number float NULL, value_date datetime NULL, value_flag bit NULL, CONSTRAINT PK_BPAStatistics_new primary key (sessionid, name) ); insert into BPAStatistics_new (sessionid, name, datatype, value_text, value_number, value_date, value_flag) select sessionid, name, datatype, value_text, value_number, value_date, value_flag from BPAStatistics; drop table BPAStatistics; exec sp_rename ''BPAStatistics_new'', ''BPAStatistics''; exec sp_rename ''PK_BPAStatistics_new'', ''PK_BPAStatistics''; ALTER TABLE BPATag ALTER COLUMN tag nvarchar(255); ALTER TABLE BPAValCategory ALTER COLUMN description nvarchar(255); ')exec('')exec('ALTER TABLE BPAWorkQueueLog ALTER COLUMN keyvalue nvarchar(255); ALTER TABLE BPAValAction ALTER COLUMN description nvarchar(255); ALTER TABLE BPAWebService ALTER COLUMN servicename nvarchar(128); ALTER TABLE BPAWebService ALTER COLUMN url nvarchar(2083); ALTER TABLE BPAWebService ALTER COLUMN wsdl nvarchar(max); ALTER TABLE BPAWebService ALTER COLUMN settingsXML nvarchar(max); ALTER TABLE BPAValType ALTER COLUMN description nvarchar(255); exec bpa_sp_dropunique ''BPAWorkQueueFilter'', ''FilterName''; ALTER TABLE BPAWorkQueueFilter ALTER COLUMN FilterName nvarchar(32); ALTER TABLE BPAWorkQueueFilter ALTER COLUMN FilterXML nvarchar(max); ALTER TABLE BPAWorkQueueFilter ADD CONSTRAINT UNQ_BPAWorkQueueFilter_FilterName unique (FilterName); ')exec('')exec('ALTER TABLE BPAWorkQueue ALTER COLUMN name nvarchar(255); ALTER TABLE BPAWorkQueue ALTER COLUMN keyfield nvarchar(255); if not exists (select 1 from BPADBVersion where dbversion=''193'') exec('' ALTER TABLE BPAWorkQueue ALTER COLUMN encryptname nvarchar(255);''); ALTER TABLE BPAValCheck ALTER COLUMN description nvarchar(255); ALTER TABLE BPATask ALTER COLUMN name nvarchar(128); ALTER TABLE BPATask ALTER COLUMN description nvarchar(max); ALTER TABLE BPATaskSession ALTER COLUMN processparams nvarchar(max); ALTER TABLE BPATaskSession ALTER COLUMN resourcename nvarchar(128); ')exec('')exec('ALTER TABLE BPAAlertEvent ALTER COLUMN Message nvarchar(500); exec bpa_sp_dropdefault ''BPASysConfig'', ''ActiveDirectoryProvider''; exec bpa_sp_dropdefault ''BPASysConfig'', ''ArchivingFolder''; exec bpa_sp_dropdefault ''BPASysConfig'', ''ArchivingAge''; ALTER TABLE BPASysConfig ALTER COLUMN maxnumconcproc nvarchar(100); ALTER TABLE BPASysConfig ALTER COLUMN ArchiveInProgress nvarchar(20); ALTER TABLE BPASysConfig ALTER COLUMN LicenseKey nvarchar(max); ALTER TABLE BPASysConfig ALTER COLUMN ActiveDirectoryProvider nvarchar(max); if not exists (select 1 from BPADBVersion where dbversion=''193'') exec('' ALTER TABLE BPASysConfig ALTER COLUMN credentialkey nvarchar(50);''); ALTER TABLE BPASysConfig ALTER COLUMN ArchivingFolder nvarchar(max); ALTER TABLE BPASysConfig ALTER COLUMN ArchivingAge nvarchar(max); ALTER TABLE BPASysConfig ADD DEFAULT ('''') FOR ActiveDirectoryProvider; ALTER TABLE BPASysConfig ADD DEFAULT ('''') FOR ArchivingFolder; ALTER TABLE BPASysConfig ADD DEFAULT (''6m'') FOR ArchivingAge; CREATE TABLE BPAAliveResources_new ( MachineName nvarchar(16) NOT NULL, UserID uniqueidentifier NOT NULL, LastUpdated datetime NOT NULL, CONSTRAINT PK_BPAAliveResources_new PRIMARY KEY CLUSTERED (MachineName, UserID) ); INSERT INTO BPAAliveResources_new (MachineName,UserID,LastUpdated) SELECT MachineName,UserID,LastUpdated FROM BPAAliveResources; drop table BPAAliveResources; exec sp_rename ''BPAAliveResources_new'', ''BPAAliveResources''; exec sp_rename ''PK_BPAAliveResources_new'', ''PK_BPAAliveResources''; exec bpa_sp_dropunique ''BPACalendar'', ''name''; ALTER TABLE BPACalendar ALTER COLUMN name nvarchar(128); ALTER TABLE BPACalendar ALTER COLUMN description nvarchar(max); ALTER TABLE BPACalendar ADD CONSTRAINT UNQ_BPACalendar_name unique (name); ')exec('')exec('ALTER TABLE BPAOldPassword ALTER COLUMN password nvarchar(128); ALTER TABLE BPAPref DROP CONSTRAINT UNQ_BPAPref_name_userid; ALTER TABLE BPAPref ALTER COLUMN name nvarchar(255); ALTER TABLE BPAPref ADD constraint UNQ_BPAPref_name_userid unique (name, userid); ALTER TABLE BPARelease DROP CONSTRAINT UNQ_BPARelease_packageid_name; ALTER TABLE BPARelease ALTER COLUMN name nvarchar(255); ALTER TABLE BPARelease ALTER COLUMN notes nvarchar(max); ALTER TABLE BPARelease ADD constraint UNQ_BPARelease_packageid_name unique (packageid, name); ALTER TABLE BPARecent ALTER COLUMN name nvarchar(128); ALTER TABLE BPAScheduleLog ALTER COLUMN servername nvarchar(255); ')exec('')exec('DROP Index IX_BPAScheduleLogEntry_logid_entrytype ON BPAScheduleLogEntry; ALTER TABLE BPAScheduleLogEntry ALTER COLUMN terminationreason nvarchar(255); ALTER TABLE BPAScheduleLogEntry ALTER COLUMN stacktrace nvarchar(max); create index IX_BPAScheduleLogEntry_logid_entrytype on BPAScheduleLogEntry(schedulelogid, entrytype) include (entrytime, terminationreason); ALTER TABLE BPAScenarioDetail ALTER COLUMN testtext nvarchar(1000); ALTER TABLE BPAReleaseEntry ALTER COLUMN typekey nvarchar(64); ALTER TABLE BPAReleaseEntry ALTER COLUMN entityid nvarchar(255); ALTER TABLE BPAReleaseEntry ALTER COLUMN name nvarchar(255); ')exec('')exec('ALTER TABLE BPAStringPref ALTER COLUMN value nvarchar(max); exec bpa_sp_dropdefault ''BPAWorkQueueItem'', ''status''; DROP INDEX Index_BPAWorkQueueItem_exceptionreasonvarchar ON BPAWorkQueueItem; DROP INDEX Index_BPAWorkQueueItem_exceptionreasontag ON BPAWorkQueueItem; ALTER TABLE BPAWorkQueueItem DROP COLUMN exceptionreasonvarchar; ALTER TABLE BPAWorkQueueItem DROP COLUMN exceptionreasontag; ALTER TABLE BPAWorkQueueItem ALTER COLUMN keyvalue nvarchar(255); ALTER TABLE BPAWorkQueueItem ALTER COLUMN status nvarchar(255); ALTER TABLE BPAWorkQueueItem ALTER COLUMN exceptionreason nvarchar(max); ALTER TABLE BPAWorkQueueItem ALTER COLUMN data nvarchar(max); ALTER TABLE BPAWorkQueueItem ADD DEFAULT ('''') FOR status; ALTER TABLE BPAWorkQueueItem ADD exceptionreasonvarchar AS (CONVERT(nvarchar(400),exceptionreason)); ALTER TABLE BPAWorkQueueItem ADD exceptionreasontag AS (CONVERT(nvarchar(415),N''Exception: ''+replace(CONVERT(nvarchar(400),exceptionreason),N'';'',N'':''))) PERSISTED; create index Index_BPAWorkQueueItem_exceptionreasonvarchar on BPAWorkQueueItem(exceptionreasonvarchar); create index Index_BPAWorkQueueItem_exceptionreasontag on BPAWorkQueueItem(exceptionreasontag); ')exec('')exec('CREATE TABLE BPADBVersion_new ( dbversion nvarchar(50) NOT NULL, scriptrundate datetime NULL, scriptname nvarchar(50) NULL, description nvarchar(200) NULL, CONSTRAINT PK_BPADBVersion_new PRIMARY KEY CLUSTERED (dbversion) ); INSERT INTO BPADBVersion_new (dbversion, scriptrundate, scriptname, description) SELECT dbversion, scriptrundate, scriptname, description FROM BPADBVersion; drop table BPADBVersion; exec sp_rename ''BPADBVersion_new'', ''BPADBVersion''; exec sp_rename ''PK_BPADBVersion_new'', ''PK_BPADBVersion''; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''182'', GETUTCDATE(), ''db_upgradeR182.sql UTC'', ''Switch to full unicode support'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='183') begin exec('update BPAPerm set name = ''System - Reporting'' where name = ''View Reports''; update BPAPermGroupMember set permgroupid = (select id from BPAPermGroup where name = ''System Manager'') where permid = (select id from BPAPerm where name = ''System - Reporting''); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''183'', GETUTCDATE(), ''db_upgradeR183.sql UTC'', ''Rename reporting permission'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='184') begin exec('alter table BPAWorkQueue add processid uniqueidentifier null constraint FK_BPAWorkQueue_BPAProcess foreign key references BPAProcess(processid), resourcegroupid uniqueidentifier null constraint FK_BPAWorkQueue_BPAGroup foreign key references BPAGroup(id), targetsessions int not null constraint DEF_BPAWorkQueue_targetsessions default 0; alter table BPASession add queueid int null constraint FK_BPASession_BPAWorkQueue foreign key references BPAWorkQueue(ident), stoprequested datetime null, stoprequestack datetime null; insert into BPAStatus (statusid, type, description) values (7, ''RUN'', ''Stopping''); ')exec('')exec('exec sp_refreshview ''BPVSession''; ')exec('')exec('alter view BPVSessionInfo as select s.sessionid as "sessionid", s.sessionnumber as "sessionnumber", s.startdatetime as "startdatetime", s.enddatetime as "enddatetime", s.processid as "processid", p.name as "processname", s.starterresourceid as "starterresourceid", sr.name as "starterresourcename", s.starteruserid as "starteruserid", isnull(su.username, ''['' + su.systemusername + '']'') as "starterusername", s.runningresourceid as "runningresourceid", rr.name as "runningresourcename", s.runningosusername as "runningosusername", s.statusid as "statusid", s.startparamsxml as "startparamsxml", s.logginglevelsxml as "logginglevelsxml", s.sessionstatexml as "sessionstatexml", s.queueid as "queueid" from BPASession s join BPAProcess p on s.processid = p.processid join BPAResource sr on s.starterresourceid = sr.resourceid join BPAResource rr on s.runningresourceid = rr.resourceid join BPAUser su on s.starteruserid = su.userid where s.statusid <> 6; ')exec('')exec('if not exists (select 1 from BPADBVersion where dbversion=''193'') exec('' alter view BPVGroupedQueues as select g.treeid as treeid, g.id as groupid, g.name as groupname, q.ident as id, q.name as name, q.id as guid, q.running as running, q.encryptname as encryptname, q.processid as processid, q.resourcegroupid as resourcegroupid, case when q.processid is not null and q.resourcegroupid is not null then cast(1 as bit) else cast(0 as bit) end as isactive from BPAWorkQueue q left join ( BPAGroupQueue gq inner join BPAGroup g on gq.groupid = g.id ) on gq.memberid = q.ident;''); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''184'', GETUTCDATE(), ''db_upgradeR184.sql UTC'', ''Adds db structure required for active work queue creation and configuration'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='185') begin exec('create table BPATileDataSources ( spname nvarchar(255) not null, tiletype int not null, helppage nvarchar(255) null, constraint PK_BPATileDataSources primary key clustered (spName) ); ')exec('')exec('update BPATile set tiletype=1; insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_AverageHandlingTime'', 1, ''AverageHandlingTime.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_AverageRetries'', 1, ''AverageRetries.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_DailyProductivity'', 1, ''DailyProductivity.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_DailyUtilisation'', 1, ''DailyUtilisation.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_Exceptions'', 1, ''Exceptions.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_FTEProductivityComparison'', 1, ''FTEProductivityComparison.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_LargestTables'', 1, ''LargestTables.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_ProcessUtilisationByHour'', 1, ''ProcessUtilisationByHour.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_ResourceUtilisationByHour'', 1, ''ResourceUtilisationByHour.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_TotalAutomations'', 1, ''TotalAutomations.htm''); insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_WorkforceAvailability'', 1, ''WorkforceAvailability.htm''); create table BPAPackageTile ( packageid int not null constraint FK_BPAPackageTile_BPAPackage foreign key references BPAPackage(id) on delete cascade, tileid uniqueidentifier not null constraint FK_BPAPackageTile_BPATile foreign key references BPATile(id) on delete cascade, constraint PK_BPAPackageTile primary key (packageid, tileid) ); create table BPAPackageDashboard ( packageid int not null constraint FK_BPAPackageDashboard_BPAPackage foreign key references BPAPackage(id) on delete cascade, dashid uniqueidentifier not null constraint FK_BPAPackageDashboard_BPADashboard foreign key references BPADashboard(id) on delete cascade, constraint PK_BPAPackageDashboard primary key (packageid, dashid) ); if object_id(''BPAPackageProcessGroupMember'') is not null drop table BPAPackageProcessGroupMember; declare @id int; insert into BPAPerm (name) values(''Import Tile''); insert into BPAPerm (name) values(''Import Global Dashboard''); select @id = id from BPAPermGroup where name=''Dashboard''; insert into BPAPermGroupMember select @id, a.id from BPAPerm a where a.name in (''Import Tile'', ''Import Global Dashboard''); select @id = id from BPAUserRole where name=''System Administrator''; insert into BPAUserRolePerm select @id, a.id from BPAPerm a where a.name in (''Import Tile'', ''Import Global Dashboard''); INSERT INTO BPADBVersion VALUES ( ''185'', GETUTCDATE(), ''db_upgradeR185.sql UTC'', ''Integrates tile help and adds tiles & dashboards to release manager'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='186') begin exec('if DATABASE_PRINCIPAL_ID(''bpa_ExecuteSP_System'') is null exec(N''CREATE ROLE bpa_ExecuteSP_System''); GRANT EXECUTE ON OBJECT::usp_RefreshMI TO bpa_ExecuteSP_System; GRANT EXECUTE ON OBJECT::usp_RefreshProductivityData TO bpa_ExecuteSP_System; GRANT EXECUTE ON OBJECT::usp_RefreshUtilisationData TO bpa_ExecuteSP_System; if DATABASE_PRINCIPAL_ID(''bpa_ExecuteSP_DataSource_bpSystem'') is null exec(N''CREATE ROLE bpa_ExecuteSP_DataSource_bpSystem''); GRANT EXECUTE ON OBJECT::BPDS_AverageHandlingTime TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_AverageRetries TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_DailyProductivity TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_DailyUtilisation TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_Exceptions TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_FTEProductivityComparison TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_LargestTables TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_ProcessUtilisationByHour TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_ResourceUtilisationByHour TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_TotalAutomations TO bpa_ExecuteSP_DataSource_bpSystem; GRANT EXECUTE ON OBJECT::BPDS_WorkforceAvailability TO bpa_ExecuteSP_DataSource_bpSystem; if DATABASE_PRINCIPAL_ID(''bpa_ExecuteSP_DataSource_custom'') is null exec(N''CREATE ROLE bpa_ExecuteSP_DataSource_custom''); ')exec('')exec('if OBJECT_ID(''ufn_GetReportDays'') is null exec(N''create function ufn_GetReportDays (@Number int) returns @Days table (TheDate datetime) as begin return; end''); if OBJECT_ID(''ufn_GetReportMonths'') is null exec(N''create function ufn_GetReportMonths (@Number int) returns @Months table (TheYear int, TheMonth int) as begin return; end''); ')exec('')exec('alter function ufn_GetReportDays ( @Number int) returns @Days table ( TheDate datetime) as begin declare @StartDate datetime; set @StartDate = DATEADD(DAY, -1, CAST(FLOOR(CAST(GETDATE() as float)) as datetime)); with CTE_DatesTable as ( select @StartDate as TheDate union all select DATEADD(DAY, -1, TheDate) from CTE_DatesTable where DATEADD(DAY, -1, TheDate) > DATEADD(DAY, -@Number, @StartDate)) insert into @Days(TheDate) select TheDate FROM CTE_DatesTable option (MAXRECURSION 0); return; end ')exec('')exec('alter function ufn_GetReportMonths ( @Number int) returns @Months table ( TheYear int, TheMonth int) as begin declare @StartDate datetime; set @StartDate = DATEADD(DAY, -(DAY(GETDATE())-1), GETDATE()); with CTE_DatesTable as ( select @StartDate as TheDate union all select DATEADD(MONTH, -1, TheDate) from CTE_DatesTable where DATEADD(MONTH, -1, TheDate) > DATEADD(MONTH, -@Number, @StartDate)) insert into @Months (TheYear, TheMonth) select YEAR(TheDate), MONTH(TheDate) FROM CTE_DatesTable option (MAXRECURSION 0); return; end ')exec('')exec('alter procedure BPDS_AverageHandlingTime @BPQueueName nvarchar(max) = null, @NumberOfDays int = 7 as if @NumberOfDays < 1 or @NumberOfDays > 90 raiserror(''@NumberOfDays must be between 1 and 90'', 11, 1); else select ISNULL(q.name, ''<unknown>''), CAST(ISNULL(AVG(d.avgworktime), 0) as decimal(12,2)) as "Average Time" from BPMIProductivityDaily d left join BPAWorkQueue q on d.queueident = q.ident where d.reportdate >= (select MIN(TheDate) from ufn_GetReportDays(@NumberOfDays)) and (@BPQueueName is null or @BPQueueName = q.name) group by q.name; return; ')exec('')exec('alter procedure BPDS_AverageRetries @BPQueueName nvarchar(max) = null, @NumberOfDays int = 7 as if @NumberOfDays < 1 or @NumberOfDays > 90 raiserror(''@NumberOfDays must be between 1 and 90'', 11, 1); else select ISNULL(q.name, ''<unknown>''), CAST(ISNULL(AVG(d.avgretries), 0) as decimal(12,2)) as "Retries" from BPMIProductivityDaily d left join BPAWorkQueue q on d.queueident = q.ident where d.reportdate >= (select MIN(TheDate) from ufn_GetReportDays(@NumberOfDays)) and (@BPQueueName is null or @BPQueueName = q.name) group by q.name; return; ')exec('')exec('alter procedure BPDS_DailyProductivity @BPQueueName nvarchar(max) = null, @NumberOfDays int = 7 as if @NumberOfDays < 1 or @NumberOfDays > 31 raiserror(''@NumberOfDays must be between 1 and 31'', 11, 1); else select DATENAME(day, dys.TheDate) + ''-'' + DATENAME(month, dys.TheDate) as "Day", ISNULL(SUM(d.created), 0) as New, ISNULL(SUM(d.deferred), 0) as Deferred, ISNULL(SUM(d.completed), 0) as Complete from ufn_GetReportDays(@NumberOfDays) dys left join BPMIProductivityDaily d on d.reportdate = dys.TheDate left join BPAWorkQueue q on d.queueident = q.ident where @BPQueueName is null or @BPQueueName = q.name group by dys.TheDate; return; ')exec('')exec('alter procedure BPDS_DailyUtilisation @BPResourceName nvarchar(max) = null, @NumberOfDays int = 7, @DisplayUnits nvarchar(max) = ''minute'', @MaxResourceHours int = 24 as if @NumberOfDays < 1 or @NumberOfDays > 31 raiserror(''@NumberOfDays must be between 1 and 31'', 11, 1); else if @DisplayUnits not in (''second'', ''minute'', ''hour'', ''percentage'') raiserror(''@DisplayUnits must be second, minute, hour or percentage'', 11, 1); else if @MaxResourceHours < 1 or @MaxResourceHours > 24 raiserror(''@MaxResourceHours must be between 1 and 24'', 11, 1); else select DATENAME(day, u.TheDate) + ''-'' + DATENAME(month, u.TheDate) as "Day", case when @DisplayUnits = ''second'' then CAST(Total as decimal(12,2)) when @DisplayUnits = ''hour'' then CAST(Total/3600 as decimal(12,2)) when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Total/(36*Resources*@MaxResourceHours) as decimal(12,2)) else CAST(Total/60 as decimal(12,2)) end as "Total" from ( select dates.TheDate, CAST(ISNULL(SUM(d.hr0 + d.hr1 + d.hr2 + d.hr3 + d.hr4 + d.hr5 + d.hr6 + d.hr7 + d.hr8 + d.hr9 + d.hr10 + d.hr11 + d.hr12 + d.hr13 + d.hr14 + d.hr15 + d.hr16 + d.hr17 + d.hr18 + d.hr19 + d.hr20 + d.hr21 + d.hr22 + d.hr23), 0) as float) as "Total", COUNT(distinct(d.resourceid)) as "Resources" from ufn_GetReportDays(@NumberOfDays) dates left join BPMIUtilisationDaily d on d.reportdate = dates.TheDate left join BPAResource r on d.resourceid = r.resourceid where @BPResourceName is null or @BPResourceName = r.name group by dates.TheDate ) as u; return; ')exec('')exec('alter procedure BPDS_Exceptions @BPQueueName nvarchar(max) = null, @NumberOfDays int = 3 as if @NumberOfDays < 1 or @NumberOfDays > 31 raiserror(''@NumberOfDays must be between 1 and 31'', 11, 1); else begin declare @ColumnName nvarchar(max); declare @Query nvarchar(max); declare @WhereClause nvarchar(max); set @WhereClause = ISNULL('' and q.name = '''''' + @BPQueueName + '''''''', ''''); select @ColumnName = ISNULL(@ColumnName + '','', '''') + QUOTENAME(DATENAME(day, TheDate) + ''-'' + DATENAME(month, TheDate)) from ufn_GetReportDays(@NumberOfDays) order by TheDate; set @Query = ''select name, '' + @ColumnName + '' from (select ISNULL(q.name, ''''<unknown>'''') as name, DATENAME(day, d.reportdate) + ''''-'''' + DATENAME(month, d.reportdate) as pivotdate, d.exceptioned from BPMIProductivityDaily d left join BPAWorkQueue q on d.queueident = q.ident where d.reportdate >= (select MIN(TheDate) from ufn_GetReportDays('' + CAST(@NumberOfDays as nvarchar) + '')) '' + @WhereClause + '') as src pivot (sum(exceptioned) for pivotdate in ('' + @ColumnName + '')) as pvt'' exec(@Query) end return; ')exec('')exec('alter procedure BPDS_FTEProductivityComparison @BPQueueName nvarchar(max) = null, @NumberOfMonths int = 6, @FTEProductivity decimal(12,2) = 0, @FTECost decimal(12,2) = 0, @DisplayAs nvarchar(max) = ''percentage'' as if @NumberOfMonths < 1 or @NumberOfMonths > 12 raiserror(''@NumberOfMonths must be between 1 and 12'', 11, 1); else if @DisplayAs not in (''percentage'', ''number'', ''cost'') raiserror(''@DisplayAs must be percentage, number or cost'', 11, 1); else select TheDate, case when @FTEProductivity <> 0 then case when @DisplayAs = ''cost'' then CAST((completed/(@FTEProductivity*DaysInMonth))*@FTECost as decimal(12,2)) when @DisplayAs = ''number'' then CAST(completed/(@FTEProductivity*DaysInMonth) as decimal(12,2)) else CAST((completed/(@FTEProductivity*DaysInMonth))*100 as decimal(12,2)) end else completed end from ( select DATENAME(month, DATEADD(month, mths.TheMonth, -1)) + '' '' + CAST(mths.TheYear as nvarchar(4)) as TheDate, case when mths.TheYear = DATEPART(year, getdate()) and mths.TheMonth = DATEPART(month, getutcdate()) then DAY(getdate()) else DAY(DATEADD(day, -1, DATEADD(month, 1, CAST(CAST(mths.TheYear as nvarchar) + ''-'' + CAST(mths.TheMonth as nvarchar) + ''-1'' as datetime)))) end as DaysInMonth, ISNULL(SUM(completed), 0) as Completed from ufn_GetReportMonths(@NumberOfMonths) mths left join BPMIProductivityMonthly m on m.reportyear = mths.TheYear and m.reportmonth = mths.TheMonth left join BPAWorkQueue q on m.queueident = q.ident where @BPQueueName is null or @BPQueueName = q.name group by mths.TheMonth, mths.TheYear ) as p return; ')exec('')exec('alter procedure BPDS_LargestTables @NumberOfTables int = 5 as if @NumberOfTables < 1 or @NumberOfTables > 25 raiserror(''@NumberOfTables must be between 1 and 25'', 11, 1); else select top(@NumberOfTables) t.name as "Table Name", CAST(CAST((SUM(a.total_pages)*8) as decimal)/1024 as decimal(12,2)) as "Size (Mb)" from sys.tables t inner join sys.indexes i on t.object_id = i.object_id inner join sys.partitions p on i.object_id = p.object_id and i.index_id = p.index_id inner join sys.allocation_units a on p.partition_id = a.container_id where t.name like ''BP%'' and i.object_id > 255 and i.index_id <= 1 group by t.name order by SUM(a.total_pages) desc; return; ')exec('')exec('alter procedure BPDS_ProcessUtilisationByHour @BPProcessName nvarchar(max) = null, @DisplayUnits nvarchar(max) = ''minute'' as if @DisplayUnits not in (''second'', ''minute'', ''hour'', ''percentage'') raiserror(''@DisplayUnits must be second, minute, hour or percentage'', 11, 1); else begin declare @Units int; select @Units = case when @DisplayUnits = ''second'' then 1 when @DisplayUnits = ''hour'' then 3600 else 60 end; select ProcessName, case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval1/(Resources*7200/100) as decimal(12,2)) else CAST(Interval1/@Units as decimal(12,2)) end as "00:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval2/(Resources*7200/100) as decimal(12,2)) else CAST(Interval2/@Units as decimal(12,2)) end as "02:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval3/(Resources*7200/100) as decimal(12,2)) else CAST(Interval3/@Units as decimal(12,2)) end as "04:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval4/(Resources*7200/100) as decimal(12,2)) else CAST(Interval4/@Units as decimal(12,2)) end as "06:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval5/(Resources*7200/100) as decimal(12,2)) else CAST(Interval5/@Units as decimal(12,2)) end as "08:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval6/(Resources*7200/100) as decimal(12,2)) else CAST(Interval6/@Units as decimal(12,2)) end as "10:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval7/(Resources*7200/100) as decimal(12,2)) else CAST(Interval7/@Units as decimal(12,2)) end as "12:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval8/(Resources*7200/100) as decimal(12,2)) else CAST(Interval8/@Units as decimal(12,2)) end as "14:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval9/(Resources*7200/100) as decimal(12,2)) else CAST(Interval9/@Units as decimal(12,2)) end as "16:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval10/(Resources*7200/100) as decimal(12,2)) else CAST(Interval10/@Units as decimal(12,2)) end as "18:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval11/(Resources*7200/100) as decimal(12,2)) else CAST(Interval11/@Units as decimal(12,2)) end as "20:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval12/(Resources*7200/100) as decimal(12,2)) else CAST(Interval12/@Units as decimal(12,2)) end as "22:00" from ( select p.name as ProcessName, CAST(CAST(ISNULL(SUM(d.hr0 + d.hr1), 0) as decimal) as decimal(12,2)) as "Interval1", CAST(CAST(ISNULL(SUM(d.hr2 + d.hr3), 0) as decimal) as decimal(12,2)) as "Interval2", CAST(CAST(ISNULL(SUM(d.hr4 + d.hr5), 0) as decimal) as decimal(12,2)) as "Interval3", CAST(CAST(ISNULL(SUM(d.hr6 + d.hr7), 0) as decimal) as decimal(12,2)) as "Interval4", CAST(CAST(ISNULL(SUM(d.hr8 + d.hr9), 0) as decimal) as decimal(12,2)) as "Interval5", CAST(CAST(ISNULL(SUM(d.hr10 + d.hr11), 0) as decimal) as decimal(12,2)) as "Interval6", CAST(CAST(ISNULL(SUM(d.hr12 + d.hr13), 0) as decimal) as decimal(12,2)) as "Interval7", CAST(CAST(ISNULL(SUM(d.hr14 + d.hr15), 0) as decimal) as decimal(12,2)) as "Interval8", CAST(CAST(ISNULL(SUM(d.hr16 + d.hr17), 0) as decimal) as decimal(12,2)) as "Interval9", CAST(CAST(ISNULL(SUM(d.hr18 + d.hr19), 0) as decimal) as decimal(12,2)) as "Interval10", CAST(CAST(ISNULL(SUM(d.hr20 + d.hr21), 0) as decimal) as decimal(12,2)) as "Interval11", CAST(CAST(ISNULL(SUM(d.hr22 + d.hr23), 0) as decimal) as decimal(12,2)) as "Interval12", COUNT(distinct(d.resourceid)) as "Resources" from ufn_GetReportDays(1) dates left join BPMIUtilisationDaily d on d.reportdate = dates.TheDate left join BPAProcess p on d.processid = p.processid where @BPProcessName is null or @BPProcessName = p.name group by p.name ) as u; end return; ')exec('')exec('alter procedure BPDS_ResourceUtilisationByHour @BPResourceName nvarchar(max) = null, @DisplayUnits nvarchar(max) = ''minute'' as if @DisplayUnits not in (''second'', ''minute'', ''hour'', ''percentage'') raiserror(''@DisplayUnits must be second, minute, hour or percentage'', 11, 1); else begin declare @Units decimal; select @Units = case when @DisplayUnits = ''second'' then 1 when @DisplayUnits = ''hour'' then 3600 else 60 end; select ''Utilisation'', case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval1/(Resources*7200/100) as decimal(12,2)) else CAST(Interval1/@Units as decimal(12,2)) end as "00:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval2/(Resources*7200/100) as decimal(12,2)) else CAST(Interval2/@Units as decimal(12,2)) end as "02:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval3/(Resources*7200/100) as decimal(12,2)) else CAST(Interval3/@Units as decimal(12,2)) end as "04:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval4/(Resources*7200/100) as decimal(12,2)) else CAST(Interval4/@Units as decimal(12,2)) end as "06:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval5/(Resources*7200/100) as decimal(12,2)) else CAST(Interval5/@Units as decimal(12,2)) end as "08:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval6/(Resources*7200/100) as decimal(12,2)) else CAST(Interval6/@Units as decimal(12,2)) end as "10:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval7/(Resources*7200/100) as decimal(12,2)) else CAST(Interval7/@Units as decimal(12,2)) end as "12:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval8/(Resources*7200/100) as decimal(12,2)) else CAST(Interval8/@Units as decimal(12,2)) end as "14:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval9/(Resources*7200/100) as decimal(12,2)) else CAST(Interval9/@Units as decimal(12,2)) end as "16:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval10/(Resources*7200/100) as decimal(12,2)) else CAST(Interval10/@Units as decimal(12,2)) end as "18:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval11/(Resources*7200/100) as decimal(12,2)) else CAST(Interval11/@Units as decimal(12,2)) end as "20:00", case when @DisplayUnits = ''percentage'' and Resources > 0 then CAST(Interval12/(Resources*7200/100) as decimal(12,2)) else CAST(Interval12/@Units as decimal(12,2)) end as "22:00" from ( select CAST(CAST(ISNULL(SUM(d.hr0 + d.hr1), 0) as decimal) as decimal(12,2)) as "Interval1", CAST(CAST(ISNULL(SUM(d.hr2 + d.hr3), 0) as decimal) as decimal(12,2)) as "Interval2", CAST(CAST(ISNULL(SUM(d.hr4 + d.hr5), 0) as decimal) as decimal(12,2)) as "Interval3", CAST(CAST(ISNULL(SUM(d.hr6 + d.hr7), 0) as decimal) as decimal(12,2)) as "Interval4", CAST(CAST(ISNULL(SUM(d.hr8 + d.hr9), 0) as decimal) as decimal(12,2)) as "Interval5", CAST(CAST(ISNULL(SUM(d.hr10 + d.hr11), 0) as decimal) as decimal(12,2)) as "Interval6", CAST(CAST(ISNULL(SUM(d.hr12 + d.hr13), 0) as decimal) as decimal(12,2)) as "Interval7", CAST(CAST(ISNULL(SUM(d.hr14 + d.hr15), 0) as decimal) as decimal(12,2)) as "Interval8", CAST(CAST(ISNULL(SUM(d.hr16 + d.hr17), 0) as decimal) as decimal(12,2)) as "Interval9", CAST(CAST(ISNULL(SUM(d.hr18 + d.hr19), 0) as decimal) as decimal(12,2)) as "Interval10", CAST(CAST(ISNULL(SUM(d.hr20 + d.hr21), 0) as decimal) as decimal(12,2)) as "Interval11", CAST(CAST(ISNULL(SUM(d.hr22 + d.hr23), 0) as decimal) as decimal(12,2)) as "Interval12", COUNT(distinct(r.resourceid)) as "Resources" from ufn_GetReportDays(1) dates left join BPMIUtilisationDaily d on d.reportdate = dates.TheDate left join BPAResource r on d.resourceid = r.resourceid where @BPResourceName is null or @BPResourceName = r.name ) as u; end return; ')exec('')exec('alter procedure BPDS_TotalAutomations as select case when ProcessType = ''O'' then ''Objects'' else ''Processes'' end as [Type], COUNT(*) as Total from BPAProcess where ProcessType in (''O'', ''P'') and (AttributeID & 1) = 0 group by ProcessType; return; ')exec('')exec('alter procedure BPDS_WorkforceAvailability as select ''Percentage'' as Label, CAST((CAST(r.ready as decimal)/r.total)*100 as decimal(6,2)) as "% Available" from (select SUM(case when [status] = ''Ready'' then 1 else 0 end) as ready, COUNT(*) as total from BPAResource where (AttributeID & 13) = 0) as r; return; ')exec('')exec('alter procedure usp_RefreshUtilisationData @ReportDate datetime, @DaysToKeep int, @MonthsToKeep int as declare @ReportTo datetime; declare @DailyUtilisation table ( resourceid uniqueidentifier, processid uniqueidentifier, h0 int, h1 int, h2 int, h3 int, h4 int, h5 int, h6 int, h7 int, h8 int, h9 int, h10 int, h11 int, h12 int, h13 int, h14 int, h15 int, h16 int, h17 int, h18 int, h19 int, h20 int, h21 int, h22 int, h23 int); set @ReportTo = DATEADD(DAY, 1, @ReportDate); with hours5 as ( select 0 as h union all select 0 union all select 0 union all select 0 union all select 0), hours25 as ( select ROW_NUMBER() over(order by a.h) - 1 as h from hours5 a cross join hours5 b) insert into @DailyUtilisation select resourceid, processid, [0],[1],[2],[3],[4],[5], [6],[7],[8],[9],[10],[11], [12],[13],[14],[15],[16],[17], [18],[19],[20],[21],[22],[23] from( select tp.resourceid, tp.processid, [Hour], case when tp.startdatetime < intervals.StartDate then case when ISNULL(tp.enddatetime, @ReportTo) > intervals.EndDate then DATEDIFF(SECOND, intervals.StartDate, intervals.EndDate) when ISNULL(tp.enddatetime, @ReportTo) between intervals.StartDate and intervals.EndDate then DATEDIFF(SECOND, intervals.StartDate, ISNULL(tp.enddatetime, @ReportTo)) else 0 end when tp.startdatetime between intervals.StartDate and intervals.EndDate then case when ISNULL(tp.enddatetime, @ReportTo) > intervals.EndDate then DATEDIFF(SECOND, tp.startdatetime, intervals.EndDate) else DATEDIFF(SECOND, tp.startdatetime, ISNULL(tp.enddatetime, @ReportTo)) end else 0 end as Duration from BPMIUtilisationShadow tp inner join hours25 hrs on hrs.h between 0 and 23 cross apply ( select hrs.h as [Hour], DATEADD(HOUR, hrs.h, @ReportDate) as StartDate, DATEADD(HOUR, hrs.h + 1, @ReportDate) as EndDate) as intervals ) as src pivot (SUM(Duration) for [Hour] in ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23])) as piv; insert into BPMIUtilisationDaily select @ReportDate, * from @DailyUtilisation; update BPMIUtilisationMonthly set hr0 = hr0 + d.h0, hr1 = hr1 + d.h1, hr2 = hr2 + d.h2, hr3 = hr3 + d.h3, hr4 = hr4 + d.h4, hr5 = hr5 + d.h5, hr6 = hr6 + d.h6, hr7 = hr7 + d.h7, hr8 = hr8 + d.h8, hr9 = hr9 + d.h9, hr10 = hr10 + d.h10, hr11 = hr11 + d.h11, hr12 = hr12 + d.h12, hr13 = hr13 + d.h13, hr14 = hr14 + d.h14, hr15 = hr15 + d.h15, hr16 = hr16 + d.h16, hr17 = hr17 + d.h17, hr18 = hr18 + d.h18, hr19 = hr19 + d.h19, hr20 = hr20 + d.h20, hr21 = hr21 + d.h21, hr22 = hr22 + d.h22, hr23 = hr23 + d.h23 from BPMIUtilisationMonthly m inner join @DailyUtilisation d on m.resourceid = d.resourceid and m.processid = d.processid where m.reportyear = DATEPART(YEAR, @ReportDate) and m.reportmonth = DATEPART(MONTH, @ReportDate); insert into BPMIUtilisationMonthly select DATEPART(YEAR, @ReportDate), DATEPART(MONTH, @ReportDate), d.* from @DailyUtilisation d left join BPMIUtilisationMonthly m on d.resourceid = m.resourceid and d.processid = m.processid and m.reportyear = DATEPART(YEAR, @ReportDate) and m.reportmonth = DATEPART(MONTH, @ReportDate) where m.reportyear is null; delete from BPMIUtilisationDaily where reportdate < DATEADD(DAY, -@DaysToKeep, @ReportDate); delete from BPMIUtilisationMonthly where reportyear <= DATEPART(YEAR, (DATEADD(MONTH, -@MonthsToKeep, @ReportDate))) and reportmonth < DATEPART(MONTH, (DATEADD(MONTH, -@MonthsToKeep, @ReportDate))); delete from BPMIUtilisationShadow where enddatetime is not null and enddatetime < @ReportDate; return; ')exec('')exec('alter procedure usp_RefreshProductivityData @ReportDate datetime, @DaysToKeep int, @MonthsToKeep int as declare @ReportTo datetime; declare @DailyProductivity table ( queueident int, created int, deferred int, retried int, exceptioned int, completed int, minworktime int, avgworktime decimal(12,2), maxworktime int, minelapsedtime int, avgelapsedtime decimal(12,2), maxelapsedtime int, minretries int, avgretries decimal(12,2), maxretries int); set @ReportTo = DATEADD(DAY, 1, @ReportDate); insert into @DailyProductivity select queueident, SUM(case when eventid = 1 then 1 else 0 end), SUM(case when eventid = 3 then 1 else 0 end), SUM(case when eventid = 4 then 1 when eventid = 8 then 1 else 0 end), SUM(case when eventid = 6 then 1 else 0 end), SUM(case when eventid = 5 then 1 else 0 end), MIN(case when eventid = 5 and worktime > 0 then worktime else 0 end), AVG(case when eventid = 5 and worktime > 0 then CAST(worktime as float) else 0 end), MAX(case when eventid = 5 and worktime > 0 then worktime else 0 end), MIN(case when eventid = 5 then elapsedtime else 0 end), AVG(case when eventid = 5 then CAST(elapsedtime as float) else 0 end), MAX(case when eventid = 5 then elapsedtime else 0 end), MIN(case when eventid = 5 then attempt-1 else 0 end), AVG(case when eventid = 5 then CAST(attempt-1 as float) else 0 end), MAX(case when eventid = 5 then attempt-1 else 0 end) from BPMIProductivityShadow where eventdatetime >= @ReportDate and eventdatetime < @ReportTo group by queueident; insert into BPMIProductivityDaily select @ReportDate, * from @DailyProductivity; update BPMIProductivityMonthly set created = m.created + d.created, deferred = m.deferred + d.deferred, retried = m.retried + d.retried, exceptioned = m.exceptioned + d.exceptioned, completed = m.completed + d.completed, minelapsedtime = (case when d.minelapsedtime < m.minelapsedtime then d.minelapsedtime else m.minelapsedtime end), avgelapsedtime = (case when m.completed + d.completed > 0 then ((m.completed * m.avgelapsedtime) + (d.completed * d.avgelapsedtime)) / (m.completed + d.completed) else 0 end), maxelapsedtime = (case when d.maxelapsedtime > m.maxelapsedtime then d.maxelapsedtime else m.maxelapsedtime end), minworktime = (case when d.minworktime < m.minworktime then d.minworktime else m.minworktime end), avgworktime = (case when m.completed + d.completed > 0 then ((m.completed * m.avgworktime) + (d.completed * d.avgworktime)) / (m.completed + d.completed) else 0 end), maxworktime = (case when d.maxworktime > m.maxworktime then d.maxworktime else m.maxworktime end), minretries = (case when d.minretries < m.minretries then d.minretries else m.minretries end), avgretries = (case when m.completed + d.retried > 0 then ((m.completed * m.avgretries) + (d.completed * d.avgretries)) / (m.completed + d.retried) else 0 end), maxretries = (case when d.maxretries > m.maxretries then d.maxretries else m.maxretries end) from BPMIProductivityMonthly m inner join @DailyProductivity d on m.queueident = d.queueident where m.reportyear = DATEPART(YEAR, @ReportDate) and m.reportmonth = DATEPART(MONTH, @ReportDate); insert into BPMIProductivityMonthly select DATEPART(YEAR, @ReportDate), DATEPART(MONTH, @ReportDate), d.* from @DailyProductivity d left join BPMIProductivityMonthly m on d.queueident = m.queueident and m.reportyear = DATEPART(YEAR, @ReportDate) and m.reportmonth = DATEPART(MONTH, @ReportDate) where m.reportyear is null; delete from BPMIProductivityDaily where reportdate < DATEADD(DAY, -@DaysToKeep, @ReportDate); delete from BPMIProductivityMonthly where reportyear <= DATEPART(YEAR, (DATEADD(MONTH, -@MonthsToKeep, @ReportDate))) and reportmonth < DATEPART(MONTH, (DATEADD(MONTH, -@MonthsToKeep, @ReportDate))); delete from BPMIProductivityShadow where eventdatetime < @ReportDate; return; ')exec('')exec('alter procedure usp_RefreshMI as declare @Today datetime, @LastRefresh datetime, @ReportDate datetime, @DaysToKeep int, @MonthsToKeep int, @MIEnabled bit; select @MIEnabled=mienabled, @DaysToKeep=dailyfor, @MonthsToKeep=monthlyfor, @LastRefresh=lastrefresh from BPAMIControl where id=1; if @MIEnabled=0 return; set @Today=CAST(FLOOR(CAST(GETDATE() as float)) as datetime); if @LastRefresh is null set @ReportDate=CAST(FLOOR(CAST(DATEADD(DAY, -1, @Today) as float)) as datetime); else set @ReportDate=CAST(FLOOR(CAST(DATEADD(DAY, 1, @LastRefresh) as float)) as datetime); update BPAMIControl set refreshinprogress=1 where id=1 and refreshinprogress=0; if @@ROWCOUNT <> 1 return; begin try while @ReportDate<@Today begin begin transaction; exec usp_RefreshUtilisationData @ReportDate, @DaysToKeep, @MonthsToKeep; exec usp_RefreshProductivityData @ReportDate, @DaysToKeep, @MonthsToKeep; update BPAMIControl set lastrefresh=@ReportDate where id=1; commit; set @ReportDate=DATEADD(DAY, 1, @ReportDate); end end try begin catch rollback; declare @ErrMsg nvarchar(4000), @ErrSeverity int select @ErrMsg=ERROR_MESSAGE(), @ErrSeverity=ERROR_SEVERITY() raiserror(@ErrMsg, @ErrSeverity, 1) end catch update BPAMIControl set refreshinprogress=0 where id=1; return; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''186'', GETUTCDATE(), ''db_upgradeR186.sql UTC'', ''Adds Blue Prism database roles and refreshes dashboard stored procedures'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='187') begin exec('if not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_QueueVolumesNow'') exec(N''create procedure BPDS_QueueVolumesNow as begin set nocount on; end''); ')exec('')exec('alter procedure BPDS_QueueVolumesNow @BPQueueName nvarchar(max) = null, @ExcludePending nvarchar(max) = ''False'', @ExcludeDeferred nvarchar(max) = ''False'', @ExcludeComplete nvarchar(max) = ''False'', @ExcludeExceptions nvarchar(max) = ''False'' as if @ExcludePending not in (''True'', ''False'') raiserror(''@ExcludePending must be either True or False'', 11, 1); else if @ExcludeDeferred not in (''True'', ''False'') raiserror(''@ExcludeDeferred must be either True or False'', 11, 1); else if @ExcludeComplete not in (''True'', ''False'') raiserror(''@ExcludeComplete must be either True or False'', 11, 1); else if @ExcludeExceptions not in (''True'', ''False'') raiserror(''@ExcludeExceptions must be either True or False'', 11, 1); else begin declare @ColumnNames nvarchar(max); select @ColumnNames = ISNULL(@ColumnNames + '','', '''') + QUOTENAME(ItemStatus) from ( select ''Pending'' as ItemStatus where @ExcludePending=''False'' union select ''Deferred'' as ItemStatus where @ExcludeDeferred=''False'' union select ''Complete'' as ItemStatus where @ExcludeComplete=''False'' union select ''Exceptions'' as ItemStatus where @ExcludeExceptions=''False'') as StatusNarrs; declare @WhereClause nvarchar(max); set @WhereClause = ISNULL('' and q.name = '''''' + @BPQueueName + '''''''', ''''); declare @SQLQuery nvarchar(max); set @SQLQuery = ''with results as ( select q.name, case when i.state = 1 then ''''Pending'''' when i.state = 3 then ''''Deferred'''' when i.state = 4 then ''''Complete'''' when i.state = 5 then ''''Exceptions'''' end as state, COUNT(*) as Number from BPAWorkQueue q inner join BPAWorkQueueItem i on i.queueident=q.ident where i.state in (1,3,4,5)'' + @WhereClause + '' group by q.name, i.state) select name, '' + @ColumnNames + '' from results pivot (SUM(Number) for state in ('' + @ColumnNames + '')) as number''; exec(@SQLQuery); end return; ')exec('')exec('insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_QueueVolumesNow'', 1, ''QueueVolumesNow.htm''); GRANT EXECUTE ON OBJECT::BPDS_QueueVolumesNow TO bpa_ExecuteSP_DataSource_bpSystem; insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Queue Volumes Now'',1,''Queue volumes by status'',0,''<Chart type="4" plotByRow="false"><Procedure name="BPDS_QueueVolumesNow" /></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Pending Queue Volumes'',1,''Pending Queue Volumes'',0,''<Chart type="6" plotByRow="false"><Procedure name="BPDS_QueueVolumesNow"><Param name="@ExcludeDeferred">True</Param><Param name="@ExcludeComplete">True</Param><Param name="@ExcludeExceptions">True</Param></Procedure></Chart>''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''Largest Database Tables (Column)'',1,''The largest ten tables in the database (Mb)'',0,''<Chart type="3" plotByRow="false"><Procedure name="BPDS_LargestTables"><Param name="@NumberOfTables">10</Param></Procedure></Chart>''); delete from BPADashboardTile where dashid=''00000000-0000-0000-0000-000000000000''; insert into BPADashboardTile (dashid, tileid, displayorder, width, height) select ''00000000-0000-0000-0000-000000000000'', t.id, 1, 1, 1 from BPATile t where t.name in (''Workforce Availability''); insert into BPADashboardTile (dashid, tileid, displayorder, width, height) select ''00000000-0000-0000-0000-000000000000'', t.id, 2, 1, 1 from BPATile t where t.name in (''Total Automations''); insert into BPADashboardTile (dashid, tileid, displayorder, width, height) select ''00000000-0000-0000-0000-000000000000'', t.id, 3, 1, 1 from BPATile t where t.name in (''Queue Volumes Now''); insert into BPADashboardTile (dashid, tileid, displayorder, width, height) select ''00000000-0000-0000-0000-000000000000'', t.id, 4, 3, 1 from BPATile t where t.name in (''Largest Database Tables (Column)''); INSERT INTO BPADBVersion VALUES ( ''187'', GETUTCDATE(), ''db_upgradeR187.sql UTC'', ''Adds additional dashboard tiles'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='188') begin exec('alter table BPAWorkQueue add activelock uniqueidentifier null, activelocktime datetime null, activelockname nvarchar(255) null; INSERT INTO BPADBVersion VALUES ( ''188'', GETUTCDATE(), ''db_upgradeR188.sql UTC'', ''Adds lock for active queues'''' aiming operations'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='189') begin exec('alter view BPVGroupedProcessesObjects as select g.treeid as treeid, g.id as groupid, g.name as groupname, p.processid as id, p.name as name, p.ProcessType as processtype, p.description as description, p.createdate as createddate, cu.username as createdby, p.lastmodifieddate as lastmodifieddate, mu.username as lastmodifiedby, p.attributeid as attributes, pl.lockdatetime as lockdatetime, pl.userid as lockuser, pl.resourceid as lockresource from BPAProcess p join BPAUser cu on p.createdby = cu.userid join BPAUser mu on p.lastmodifiedby = mu.userid left join ( BPAGroupProcess gp inner join BPAGroup g on gp.groupid = g.id ) on gp.processid = p.processid left join BPAProcessLock pl on pl.processid = p.processid; ')exec('')exec('exec sp_refreshview ''BPVGroupedProcesses''; exec sp_refreshview ''BPVGroupedObjects''; INSERT INTO BPADBVersion VALUES ( ''189'', GETUTCDATE(), ''db_upgradeR189.sql UTC'', ''Adds lock information to process/objects group view'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='190') begin exec('update BPAPerm set name = ''System - Single Sign On'' where name = ''Workflow - Single Sign On''; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''190'', GETUTCDATE(), ''db_upgradeR190.sql UTC'', ''Rename single sign-on permission'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='191') begin exec('alter table BPASysConfig add unicodeLogging bit not null default 0; ')exec('')exec('update BPASysConfig set unicodeLogging=1 where (select COUNT(sessionnumber) from BPASessionLog) > 0; EXEC sp_rename ''BPASessionLog_v4'',''BPASessionLog_NonUnicode'' EXEC sp_rename ''PK_BPASessionLog_v4'',''PK_BPASessionLog_NonUnicode'' EXEC sp_rename ''FK_BPASessionLog_BPASession_v4'', ''FK_BPASessionLog_NonUnicode_BPASession'' EXEC sp_rename ''BPASessionLog'',''BPASessionLog_Unicode'' EXEC sp_rename ''PK_BPASessionLog'',''PK_BPASessionLog_Unicode'' EXEC sp_rename ''FK_BPASessionLog_BPASession'', ''FK_BPASessionLog_Unicode_BPASession'' create index Index_SessionStageType on BPASessionLog_Unicode(sessionnumber, stagetype) INSERT INTO BPADBVersion VALUES ( ''191'', GETUTCDATE(), ''db_upgradeR191.sql UTC'', ''Adds Unicode logging option and renames session log tables'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='192') begin exec('alter view BPVGroupedResources as select g.treeid as treeid, g.id as groupid, g.name as groupname, r.resourceid as id, r.name as name, r.attributeid as attributes, case when r.pool is not null then 1 else 0 end as ispoolmember, r.status as status from BPAResource r left join ( BPAGroupResource gr inner join BPAGroup g on gr.groupid = g.id ) on gr.memberid = r.resourceid; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''192'', GETUTCDATE(), ''db_upgradeR192.sql UTC'', ''Adds info about pool membership to resource group view'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='193') begin exec('') end
if not exists (select 1 from BPADBVersion where dbversion='194') begin exec('if not exists (select 1 from BPADBVersion where dbversion=''193'') begin exec('' create table BPAKeyStore ( id int identity not null, name nvarchar(255) not null, location int not null, isavailable bit not null, method int, encryptkey nvarchar(255), constraint PK_BPAKeyStore primary key (id), constraint Index_BPAKeyStore_name unique (name)); alter table BPAWorkQueue add encryptid int constraint FK_BPAWorkQueue_BPAKeyStore foreign key references BPAKeyStore (id); alter table BPAWorkQueueItem add encryptid int constraint FK_BPAWorkQueueItem_BPAKeyStore foreign key references BPAKeyStore (id); alter table BPASysConfig add encryptid int constraint FK_BPASysConfig_BPAKeyStore foreign key references BPAKeyStore (id); alter table BPACredentials add encryptid int constraint FK_BPACredentials_BPAKeyStore foreign key references BPAKeyStore (id);''); exec('' insert into BPAKeyStore (name, location, isavailable, method, encryptkey) select ''''Credentials Key'''', case when credentialkey is not null then 0 else 1 end, 1, 1, credentialkey from BPASysConfig; declare @id int; select @id = id from BPAKeyStore where name=''''Credentials Key''''; update BPASysConfig set encryptid=@id; update BPACredentials set encryptid=@id; update BPAWorkQueue set encryptid=@id where encryptname is not null; update i set i.encryptid=q.encryptid from BPAWorkQueue q inner join BPAWorkQueueItem i on i.queueident=q.ident where q.encryptname is not null; alter table BPAWorkQueue drop column encryptname; alter table BPASysConfig drop column credentialkey;''); end ')exec('')exec('declare @id int; insert into BPAPerm values(''Security - View Encryption Schemes''); insert into BPAPerm values(''Security - Manage Encryption Schemes''); select @id = id from BPAPermGroup where name=''System Manager''; insert into BPAPermGroupMember select @id, a.id from BPAPerm a where a.name in (''Security - View Encryption Schemes'', ''Security - Manage Encryption Schemes''); select @id = id from BPAUserRole where name=''System Administrator''; insert into BPAUserRolePerm select @id, a.id from BPAPerm a where a.name in (''Security - View Encryption Schemes'', ''Security - Manage Encryption Schemes''); ')exec('')exec('alter view BPVGroupedQueues as select g.treeid as treeid, g.id as groupid, g.name as groupname, q.ident as id, q.name as name, q.id as guid, q.running as running, q.encryptid as encryptid, q.processid as processid, q.resourcegroupid as resourcegroupid, case when q.processid is not null and q.resourcegroupid is not null then cast(1 as bit) else cast(0 as bit) end as isactive from BPAWorkQueue q left join ( BPAGroupQueue gq inner join BPAGroup g on gq.groupid = g.id ) on gq.memberid = q.ident; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''194'', GETUTCDATE(), ''db_upgradeR194.sql UTC'', ''Adds tables for multiple encryption key support [v5]'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='196') begin exec('IF NOT EXISTS(SELECT * FROM sys.columns WHERE Name = N''ResourceRegistrationMode'' AND Object_ID = Object_ID(N''BPASysConfig'')) begin ALTER TABLE BPASysConfig ADD ResourceRegistrationMode integer NOT NULL DEFAULT 0; end IF NOT EXISTS(SELECT * FROM sys.columns WHERE Name = N''FQDN'' AND Object_ID = Object_ID(N''BPAResource'')) begin ALTER TABLE BPAResource ADD FQDN nvarchar(max) NULL; end ALTER TABLE BPASysConfig ADD PreventResourceRegistration integer NOT NULL DEFAULT 0; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''196'', GETUTCDATE(), ''db_upgradeR196.sql UTC'', ''Add fields for Resource FQDN support'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='198') begin exec('create table BPACaseLock ( id bigint not null, locktime datetime not null, sessionid uniqueidentifier null, lockid uniqueidentifier not null, constraint PK_BPACaseLock primary key clustered (id), constraint FK_CaseLock_WorkQueueItem foreign key (id) references BPAWorkQueueItem (ident), constraint FK_CaseLock_Session foreign key (sessionid) references BPASession (sessionid) ); create nonclustered index Index_BPACaseLock_sessionid on BPACaseLock(sessionid); create nonclustered index Index_BPACaseLock_lockid on BPACaseLock(lockid); ')exec('')exec('drop index Index_BPAWorkQueueItem_locked on BPAWorkQueueItem; ')exec('')exec('drop index Index_BPAWorkQueueItem_lastupdated on BPAWorkQueueItem; ')exec('')exec('alter table BPAWorkQueueItem drop column queuepositiondate, lastupdated, state, locked; ')exec('')exec('alter table BPAWorkQueueItem add lastupdated as coalesce(completed,exception,loaded) persisted; ')exec('')exec('if not exists(select * from sys.views where name = ''BPVWorkQueueItem'') exec (N''create view BPVWorkQueueItem as select 1 as placeholder''); ')exec('')exec('alter view BPVWorkQueueItem as select it.ident ,it.id ,it.queueid ,it.keyvalue ,it.status ,it.attempt ,it.loaded ,lk.locktime as locked ,it.completed ,it.exception ,it.exceptionreason ,it.deferred ,it.worktime ,it.data ,it.queueident ,coalesce(lk.sessionid,it.sessionid) as sessionid ,it.priority ,case when it.exception is null and it.completed is null and lk.locktime is null and (it.deferred is null or it.deferred<getutcdate()) then it.loaded else convert(datetime,''99991231'',0) end as queuepositiondate ,it.prevworktime ,it.attemptworktime ,it.finished ,case when it.exception is not null then 5 when it.completed is not null then 4 when (it.deferred is not null and it.deferred > getutcdate()) then 3 when lk.locktime is not null then 2 else 1 end as state ,coalesce(it.completed,it.exception,lk.locktime,it.loaded) as lastupdated ,it.exceptionreasonvarchar ,it.exceptionreasontag ,it.encryptid from BPAWorkQueueItem it left join BPACaseLock lk on it.ident = lk.id; ')exec('')exec('if not exists (select * from sys.procedures where name=''usp_gettagids'' and type=''P'') exec(N''create procedure usp_gettagids as select 1''); ')exec('')exec('alter procedure usp_gettagids @tag nvarchar(255) as declare @tags table(id int not null); if @tag is not null if @tag like ''%[_%]%'' insert into @tags select t.id from BPATag t where t.tag like @tag; else insert into @tags select t.id from BPATag t where t.tag = @tag; if exists (select * from @tags) select * from @tags; else select null; ')exec('')exec('if not exists (select * from sys.procedures where name=''usp_getnextcase'' and type=''P'') exec(N''create procedure usp_getnextcase as select 1''); ')exec('')exec('alter procedure usp_getnextcase @queuename nvarchar(255), @keyfilter nvarchar(255) = null, @sess uniqueidentifier = null, @ontag1 nvarchar(255) = null, @ontag2 nvarchar(255) = null, @ontag3 nvarchar(255) = null, @ontag4 nvarchar(255) = null, @ontag5 nvarchar(255) = null, @ontag6 nvarchar(255) = null, @ontag7 nvarchar(255) = null, @ontag8 nvarchar(255) = null, @ontag9 nvarchar(255) = null, @offtag1 nvarchar(255) = null, @offtag2 nvarchar(255) = null, @offtag3 nvarchar(255) = null, @offtag4 nvarchar(255) = null, @offtag5 nvarchar(255) = null, @offtag6 nvarchar(255) = null, @offtag7 nvarchar(255) = null, @offtag8 nvarchar(255) = null, @offtag9 nvarchar(255) = null as declare @sql nvarchar(max); declare @params nvarchar(max); declare @lockid uniqueidentifier; set @lockid = newid(); if object_id(''tempdb..#ontags'') is not null drop table #ontags; if object_id(''tempdb..#offtags'')is not null drop table #offtags; create table #ontags (id int); create table #offtags (id int); if @ontag1 is not null insert into #ontags exec usp_gettagids @tag=@ontag1; if @ontag2 is not null insert into #ontags exec usp_gettagids @tag=@ontag2; if @ontag3 is not null insert into #ontags exec usp_gettagids @tag=@ontag3; if @ontag4 is not null insert into #ontags exec usp_gettagids @tag=@ontag4; if @ontag5 is not null insert into #ontags exec usp_gettagids @tag=@ontag5; if @ontag6 is not null insert into #ontags exec usp_gettagids @tag=@ontag6; if @ontag7 is not null insert into #ontags exec usp_gettagids @tag=@ontag7; if @ontag8 is not null insert into #ontags exec usp_gettagids @tag=@ontag8; if @ontag9 is not null insert into #ontags exec usp_gettagids @tag=@ontag9; if exists (select 1 from #ontags where id is null) return; if @offtag1 is not null insert into #offtags exec usp_gettagids @tag=@offtag1; if @offtag2 is not null insert into #offtags exec usp_gettagids @tag=@offtag2; if @offtag3 is not null insert into #offtags exec usp_gettagids @tag=@offtag3; if @offtag4 is not null insert into #offtags exec usp_gettagids @tag=@offtag4; if @offtag5 is not null insert into #offtags exec usp_gettagids @tag=@offtag5; if @offtag6 is not null insert into #offtags exec usp_gettagids @tag=@offtag6; if @offtag7 is not null insert into #offtags exec usp_gettagids @tag=@offtag7; if @offtag8 is not null insert into #offtags exec usp_gettagids @tag=@offtag8; if @offtag9 is not null insert into #offtags exec usp_gettagids @tag=@offtag9; delete from #offtags where id is null; set @sql = '' insert into BPACaseLock (id,locktime,sessionid,lockid) select top 1 i.ident ,getutcdate() ,case when @sess is null then i.sessionid else @sess end ,@lockid from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident left join BPACaseLock l on l.id = i.ident where q.name = @queuename and q.running = 1 and i.finished is null and (i.deferred is null or i.deferred < getutcdate()) and l.id is null and (@keyfilter is null or i.keyvalue = @keyfilter) ''; if exists (select 1 from #ontags) begin set @sql = @sql + '' and ( select count(*) from BPAWorkQueueItemTag it join #ontags ot on it.tagid = ot.id where it.queueitemident = i.ident ) = (select count(*) from #ontags) ''; end if exists (select 1 from #offtags) begin set @sql = @sql + '' and not exists ( select 1 from BPAWorkQueueItemTag it join #offtags ot on it.tagid = ot.id where it.queueitemident = i.ident ) ''; end set @sql = @sql + '' order by i.priority, i.loaded, i.ident; ''; set @params = '' @sess uniqueidentifier, @queuename nvarchar(255), @keyfilter nvarchar(255), @lockid uniqueidentifier ''; exec sp_executesql @sql,@params,@sess=@sess,@queuename=@queuename,@keyfilter=@keyfilter,@lockid=@lockid; select i.encryptid, i.id, i.ident, i.keyvalue, i.data, i.status, i.attempt from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident join BPACaseLock l on i.ident = l.id where l.lockid = @lockid; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''198'', GETUTCDATE(), ''db_upgradeR198.sql UTC'', ''Adds new "locked item" table for queues'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='199') begin exec('if DATABASE_PRINCIPAL_ID(''bpa_ExecuteSP_System'') is not null grant execute on object::usp_gettagids to bpa_ExecuteSP_System; ')exec('')exec('if DATABASE_PRINCIPAL_ID(''bpa_ExecuteSP_System'') is not null grant execute on object::usp_getnextcase to bpa_ExecuteSP_System; ')exec('')exec('alter procedure BPDS_QueueVolumesNow @BPQueueName nvarchar(max) = null, @ExcludePending nvarchar(max) = ''False'', @ExcludeDeferred nvarchar(max) = ''False'', @ExcludeComplete nvarchar(max) = ''False'', @ExcludeExceptions nvarchar(max) = ''False'' as if @ExcludePending not in (''True'', ''False'') raiserror(''@ExcludePending must be either True or False'', 11, 1); else if @ExcludeDeferred not in (''True'', ''False'') raiserror(''@ExcludeDeferred must be either True or False'', 11, 1); else if @ExcludeComplete not in (''True'', ''False'') raiserror(''@ExcludeComplete must be either True or False'', 11, 1); else if @ExcludeExceptions not in (''True'', ''False'') raiserror(''@ExcludeExceptions must be either True or False'', 11, 1); else begin declare @ColumnNames nvarchar(max); select @ColumnNames = ISNULL(@ColumnNames + '','', '''') + QUOTENAME(ItemStatus) from ( select ''Pending'' as ItemStatus where @ExcludePending=''False'' union select ''Deferred'' as ItemStatus where @ExcludeDeferred=''False'' union select ''Complete'' as ItemStatus where @ExcludeComplete=''False'' union select ''Exceptions'' as ItemStatus where @ExcludeExceptions=''False'') as StatusNarrs; declare @WhereClause nvarchar(max); set @WhereClause = ISNULL('' and q.name = '''''' + @BPQueueName + '''''''', ''''); declare @SQLQuery nvarchar(max); set @SQLQuery = ''with results as ( select q.name, case when i.state = 1 then ''''Pending'''' when i.state = 3 then ''''Deferred'''' when i.state = 4 then ''''Complete'''' when i.state = 5 then ''''Exceptions'''' end as state, COUNT(*) as Number from BPAWorkQueue q inner join BPVWorkQueueItem i on i.queueident=q.ident where i.state in (1,3,4,5)'' + @WhereClause + '' group by q.name, i.state) select name, '' + @ColumnNames + '' from results pivot (SUM(Number) for state in ('' + @ColumnNames + '')) as number''; exec(@SQLQuery); end return; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''199'', GETUTCDATE(), ''db_upgradeR199.sql UTC'', ''Registers work queue scripts with BPA SQL security roles'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='200') begin exec('alter table BPAProcess add sharedObject bit not null default 0; ')exec('')exec('update BPAProcess set sharedObject = 1, processxml = STUFF(processxml, CHARINDEX(''>'', processxml), 0, '' shared="True"'') where processType=''O'' and name in (select distinct(refParentName) from BPAProcessParentDependency); INSERT INTO BPADBVersion VALUES ( ''200'', GETUTCDATE(), ''db_upgradeR200.sql UTC'', ''Adds Shared attribute to objects'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='201') begin exec('alter table BPAProcessLock add machinename nvarchar(128) null; ')exec('')exec('alter table BPAProcessLock drop constraint FK_BPAProcessLock_BPAResource; update BPAProcessLock set machinename = r.name from BPAProcessLock l join BPAResource r on l.resourceid = r.resourceid; alter table BPAProcessLock drop column resourceid; ')exec('')exec('alter view BPVGroupedProcessesObjects as select g.treeid as treeid, g.id as groupid, g.name as groupname, p.processid as id, p.name as name, p.ProcessType as processtype, p.description as description, p.createdate as createddate, cu.username as createdby, p.lastmodifieddate as lastmodifieddate, mu.username as lastmodifiedby, p.attributeid as attributes, pl.lockdatetime as lockdatetime, pl.userid as lockuser, pl.machinename as lockmachinename from BPAProcess p join BPAUser cu on p.createdby = cu.userid join BPAUser mu on p.lastmodifiedby = mu.userid left join ( BPAGroupProcess gp inner join BPAGroup g on gp.groupid = g.id ) on gp.processid = p.processid left join BPAProcessLock pl on pl.processid = p.processid; ')exec('')exec('exec sp_refreshview ''BPVGroupedProcesses''; exec sp_refreshview ''BPVGroupedObjects''; INSERT INTO BPADBVersion VALUES ( ''201'', GETUTCDATE(), ''db_upgradeR201.sql UTC'', ''Adds machinename column to BPAProcessLock'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='202') begin exec('ALTER TABLE BPAResource ADD ssl bit NOT NULL DEFAULT 0; ')exec('')exec('ALTER TABLE BPASysConfig ADD RequireSecuredResourceConnections integer NOT NULL DEFAULT 0; INSERT INTO BPADBVersion VALUES ( ''202'', GETUTCDATE(), ''db_upgradeR202.sql UTC'', ''Add column for Resource PC SSL status'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='203') begin exec('') end
if not exists (select 1 from BPADBVersion where dbversion='204') begin exec('if not exists (select * from sys.procedures where name=''usp_rethrow'' and type=''P'') exec(N''create procedure usp_rethrow as select 1''); ')exec('')exec('alter procedure usp_rethrow as if error_number() is null return; declare @errormessage nvarchar(4000), @errornumber int, @errorseverity int, @errorstate int, @errorline int, @errorprocedure nvarchar(200); select @errornumber = error_number(), @errorseverity = error_severity(), @errorstate = error_state(), @errorline = error_line(), @errorprocedure = isnull(error_procedure(), ''-''); if @errorstate = 0 set @errorstate = 1; select @errormessage = N''error %d, level %d, state %d, procedure %s, line %d, '' + ''message: ''+ error_message(); raiserror ( @errormessage, @errorseverity, 1, @errornumber, @errorseverity, @errorstate, @errorprocedure, @errorline ); ')exec('')exec('alter procedure usp_getnextcase @queuename nvarchar(255), @keyfilter nvarchar(255) = null, @sess uniqueidentifier = null, @ontag1 nvarchar(255) = null, @ontag2 nvarchar(255) = null, @ontag3 nvarchar(255) = null, @ontag4 nvarchar(255) = null, @ontag5 nvarchar(255) = null, @ontag6 nvarchar(255) = null, @ontag7 nvarchar(255) = null, @ontag8 nvarchar(255) = null, @ontag9 nvarchar(255) = null, @offtag1 nvarchar(255) = null, @offtag2 nvarchar(255) = null, @offtag3 nvarchar(255) = null, @offtag4 nvarchar(255) = null, @offtag5 nvarchar(255) = null, @offtag6 nvarchar(255) = null, @offtag7 nvarchar(255) = null, @offtag8 nvarchar(255) = null, @offtag9 nvarchar(255) = null as declare @sql nvarchar(max); declare @params nvarchar(max); declare @lockid uniqueidentifier; set @lockid = newid(); if object_id(''tempdb..#ontags'') is not null drop table #ontags; if object_id(''tempdb..#offtags'')is not null drop table #offtags; create table #ontags (id int); create table #offtags (id int); if @ontag1 is not null and @ontag1 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag1; if @ontag2 is not null and @ontag2 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag2; if @ontag3 is not null and @ontag3 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag3; if @ontag4 is not null and @ontag4 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag4; if @ontag5 is not null and @ontag5 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag5; if @ontag6 is not null and @ontag6 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag6; if @ontag7 is not null and @ontag7 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag7; if @ontag8 is not null and @ontag8 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag8; if @ontag9 is not null and @ontag9 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag9; if exists (select 1 from #ontags where id is null) return; if @offtag1 is not null insert into #offtags exec usp_gettagids @tag=@offtag1; if @offtag2 is not null insert into #offtags exec usp_gettagids @tag=@offtag2; if @offtag3 is not null insert into #offtags exec usp_gettagids @tag=@offtag3; if @offtag4 is not null insert into #offtags exec usp_gettagids @tag=@offtag4; if @offtag5 is not null insert into #offtags exec usp_gettagids @tag=@offtag5; if @offtag6 is not null insert into #offtags exec usp_gettagids @tag=@offtag6; if @offtag7 is not null insert into #offtags exec usp_gettagids @tag=@offtag7; if @offtag8 is not null insert into #offtags exec usp_gettagids @tag=@offtag8; if @offtag9 is not null insert into #offtags exec usp_gettagids @tag=@offtag9; delete from #offtags where id is null; set @sql = '' set transaction isolation level read uncommitted; insert into BPACaseLock (id,locktime,sessionid,lockid) select top 1 i.ident ,getutcdate() ,case when @sess is null then i.sessionid else @sess end ,@lockid from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident left join BPACaseLock l on l.id = i.ident where q.name = @queuename and q.running = 1 and i.finished is null and (i.deferred is null or i.deferred < getutcdate()) and l.id is null and (@keyfilter is null or i.keyvalue = @keyfilter) ''; if exists (select 1 from #ontags) begin set @sql = @sql + '' and ( select count(*) from BPAWorkQueueItemTag it join #ontags ot on it.tagid = ot.id where it.queueitemident = i.ident ) = (select count(*) from #ontags) ''; end declare @onwildcardsql nvarchar(max) set @onwildcardsql = '' and exists ( select 1 from BPAWorkQueueItemTag it join BPATag t on it.tagid = t.id where it.queueitemident = i.ident and t.tag like @ontag''; if @ontag1 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''1)''; if @ontag2 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''2)''; if @ontag3 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''3)''; if @ontag4 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''4)''; if @ontag5 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''5)''; if @ontag6 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''6)''; if @ontag7 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''7)''; if @ontag8 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''8)''; if @ontag9 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''9)''; if exists (select 1 from #offtags) begin set @sql = @sql + '' and not exists ( select 1 from BPAWorkQueueItemTag it join #offtags ot on it.tagid = ot.id where it.queueitemident = i.ident ) ''; end set @sql = @sql + '' order by i.priority, i.loaded, i.ident; ''; set @params = '' @sess uniqueidentifier, @queuename nvarchar(255), @keyfilter nvarchar(255), @lockid uniqueidentifier, @ontag1 nvarchar(255), @ontag2 nvarchar(255), @ontag3 nvarchar(255), @ontag4 nvarchar(255), @ontag5 nvarchar(255), @ontag6 nvarchar(255), @ontag7 nvarchar(255), @ontag8 nvarchar(255), @ontag9 nvarchar(255) ''; declare @attempt int, @maxattempts int; set @maxattempts = 100; set @attempt = 1; while @attempt <= @maxattempts begin begin try exec sp_executesql @sql,@params,@sess=@sess,@queuename=@queuename,@keyfilter=@keyfilter,@lockid=@lockid,@ontag1=@ontag1,@ontag2=@ontag2,@ontag3=@ontag3,@ontag4=@ontag4,@ontag5=@ontag5,@ontag6=@ontag6,@ontag7=@ontag7,@ontag8=@ontag8,@ontag9=@ontag9; break; end try begin catch if error_number() = 2627 begin set @attempt = @attempt + 1; if @attempt <= @maxattempts continue; end; exec usp_rethrow; return; end catch end; select i.encryptid, i.id, i.ident, i.keyvalue, i.data, i.status, i.attempt from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident join BPACaseLock l on i.ident = l.id where l.lockid = @lockid; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''204'', GETUTCDATE(), ''db_upgradeR204.sql UTC'', ''Updates "get next" call to retry on collision'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='205') begin exec('alter table BPAUser add lastsignedin datetime null; INSERT INTO BPADBVersion VALUES ( ''205'', GETUTCDATE(), ''db_upgradeR205.sql UTC'', ''Adds last signed in column to user table'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='206') begin exec('if DATABASE_PRINCIPAL_ID(''bpa_ExecuteSP_System'') is not null grant execute on object::usp_rethrow to bpa_ExecuteSP_System; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''206'', GETUTCDATE(), ''db_upgradeR206.sql UTC'', ''Add appropriate EXEC permission to usp_rethrow'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='207') begin exec('alter table BPAPackageEnvironmentVar drop constraint FK_BPAPackageEnvironmentVar_BPAEnvironmentVar; alter table BPAPackageEnvironmentVar add constraint FK_BPAPackageEnvironmentVar_BPAEnvironmentVar foreign key (name) references BPAEnvironmentVar(name) on update cascade on delete cascade; delete from BPAPackageEnvironmentVar where packageid in (select v.packageid from BPAPackageEnvironmentVar v left join BPAPackage p on v.packageid=p.id where p.id is null) alter table BPAPackageEnvironmentVar add constraint FK_BPAPackageEnvironmentVar_BPAPackage foreign key (packageid) references BPAPackage(id) on delete cascade; INSERT INTO BPADBVersion VALUES ( ''207'', GETUTCDATE(), ''db_upgradeR207.sql UTC'', ''Restore foreign keys on Packaged Environment variable table'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='208') begin exec('alter view BPVGroupedProcessesObjects as select g.treeid as treeid, g.id as groupid, g.name as groupname, p.processid as id, p.name as name, p.ProcessType as processtype, p.description as description, p.createdate as createddate, cu.username as createdby, p.lastmodifieddate as lastmodifieddate, mu.username as lastmodifiedby, p.attributeid as attributes, pl.lockdatetime as lockdatetime, pl.userid as lockuser, pl.machinename as lockmachinename, p.wspublishname as webservicename from BPAProcess p join BPAUser cu on p.createdby = cu.userid join BPAUser mu on p.lastmodifiedby = mu.userid left join ( BPAGroupProcess gp inner join BPAGroup g on gp.groupid = g.id ) on gp.processid = p.processid left join BPAProcessLock pl on pl.processid = p.processid; ')exec('')exec('exec sp_refreshview ''BPVGroupedProcesses''; exec sp_refreshview ''BPVGroupedObjects''; INSERT INTO BPADBVersion VALUES ( ''208'', GETUTCDATE(), ''db_upgradeR208.sql UTC'', ''Add web service exposed name to object/process group view'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='209') begin exec('create table BPALicense ( id int identity constraint PK_BPALicense primary key, licensekey nvarchar(max) not null, installedon datetime not null, installedby uniqueidentifier null, constraint FK_License_User foreign key (installedby) references BPAUser (userid) ); insert into BPALicense (licensekey, installedon) select licensekey, getutcdate() from BPASysConfig; alter table BPASysConfig drop column licensekey; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''209'', GETUTCDATE(), ''db_upgradeR209.sql UTC'', ''Add multi-license table'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='210') begin exec('alter table BPAInternalAuth add Roles nvarchar(max) default ''''; INSERT INTO BPADBVersion VALUES ( ''210'', GETUTCDATE(), ''db_upgradeR210.sql UTC'', ''Add roles column to auth token table'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='211') begin exec('insert into BPAUser (userid, systemusername) values (newid(), ''Anonymous Resource''); INSERT INTO BPADBVersion VALUES ( ''211'', GETUTCDATE(), ''db_upgradeR211.sql UTC'', ''Add anonymous resource to BPAUser'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='212') begin exec('declare @id int; insert into BPAPerm (name) values(''Security - User Roles''); select @id = id from BPAPerm where name = ''Security - User Roles''; insert into BPAPermGroupMember (permgroupid, permid) select g.id, @id from BPAPermGroup g where g.name = ''System Manager''; insert into BPAUserRolePerm (userroleid, permid) select r.userroleid, @id from BPAUserRolePerm r inner join BPAPerm p on p.id = r.permid where p.name = ''Security - Users''; select @id = id from BPAPerm where name = ''Security - Password Options'' update BPAPerm set name = ''Security - Sign-on Settings'' where id = @id; insert into BPAUserRolePerm (userroleid, permid) select r.userroleid, @id from BPAUserRolePerm r inner join BPAPerm p on p.id = r.permid where p.name = ''System - Single Sign On'' and not exists (select 1 from BPAUserRolePerm e where e.userroleid = r.userroleid and e.permid = @id); select @id = id from BPAPerm where name = ''System - Single Sign On''; delete from BPAUserRolePerm where permid = @id; delete from BPAPermGroupMember where permid = @id; delete from BPAPerm where id = @id; update BPAUserRole set name = ''Runtime Resource - Backup'' where name = ''Runtime Resource'' insert into BPAUserRole values(''Runtime Resource'',null); select @id = id from BPAUserRole where name = ''Runtime Resource''; insert into BPAUserRolePerm (userroleid, permid) select @id, p.id from BPAPerm p where p.name in ( ''Audit - Business Object Logs'', ''Audit - Process Logs'', ''View Business Object'', ''View Process'', ''Read-Only Access to Queue Management'', ''Full Access to Session Management''); insert into BPAUserRoleAssignment (userid, userroleid) select u.userid, @id from BPAUser u where u.systemusername = ''Anonymous Resource'' alter table BPAInternalAuth add LoggedInMode int default 0; select @id = id from BPAPerm where name = ''Security - Credentials'' update BPAPerm set name = ''Security - Manage Credentials'' where id = @id; select @id = id from BPAPerm where name = ''Security - View Encryption Schemes'' update BPAPerm set name = ''Security - View Encryption Scheme Configuration'' where id = @id; INSERT INTO BPADBVersion VALUES ( ''212'', GETUTCDATE(), ''db_upgradeR212.sql UTC'', ''Permissions amendments'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='213') begin exec('update BPAPerm set name = ''Read Access to Queue Management'' where name = ''Read-Only Access to Queue Management'' update BPAPerm set name = ''Read Access to Session Management'' where name = ''Read-Only Access to Session Management'' INSERT INTO BPADBVersion VALUES ( ''213'', GETUTCDATE(), ''db_upgradeR213.sql UTC'', ''Rename permissions (bg-221)'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='214') begin exec('ALTER TABLE BPAPasswordRules ADD numberofrepeats INT NOT NULL DEFAULT 0; ')exec('')exec('ALTER TABLE BPAPasswordRules ADD numberofdays INT NOT NULL DEFAULT 0; ')exec('')exec('DECLARE @sql AS NVARCHAR(MAX); SET @sql = '' UPDATE BPAPasswordRules SET numberofrepeats = (SELECT CASE norepeats WHEN 1 THEN COALESCE((SELECT numberofrepeatsordays),0) ELSE 0 END), numberofdays = (SELECT CASE norepeatsdays WHEN 1 THEN COALESCE((SELECT numberofrepeatsordays),0) ELSE 0 END) ''; EXEC sp_executesql @sql; ')exec('')exec('EXEC bpa_sp_dropdefault BPAPasswordRules, numberofrepeatsordays; ')exec('')exec('ALTER TABLE BPAPasswordRules DROP COLUMN numberofrepeatsordays; ')exec('')exec('INSERT INTO BPADBVersion VALUES (''214'', GETUTCDATE(), ''db_upgradeR214.sql UTC'', ''Add additional columns for password rules number of repeats and number of days, drop column numberofrepeatsordays'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='215') begin exec('create table [BPAPassword] ( [id] int not null primary key identity, [userid] uniqueidentifier not null constraint FK_BPAPassword_BPAUser foreign key references BPAUser(userid) on delete cascade, [active] bit not null, [type] int not null, [salt] varchar(max) not null, [hash] varchar(max) not null, [lastuseddate] datetime null, ) if exists (select 1 from BPASysConfig where ActiveDirectoryProvider is null or ActiveDirectoryProvider = '''') begin insert into BPAPassword ([active],[type],[userid],[salt],[hash],[lastuseddate]) select 1, 0, u.[userid], '''', u.[password], u.[lastsignedin] from BPAUser u where u.[password] is not null; insert into BPAPassword ([active],[type],[userid],[salt],[hash],[lastuseddate]) select 0, 0, o.[userid], '''', o.[password], o.[lastuseddate] from BPAOldPassword o; end; ')exec('')exec('alter table [BPAUser] drop column [password]; drop table [BPAOldPassword]; ')exec('')exec('INSERT INTO BPADBVersion VALUES (''215'', GETUTCDATE(), ''db_upgradeR215.sql UTC'', ''Add additional columns for password hashes'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='216') begin exec('alter table BPASysConfig alter column ArchiveInProgress nvarchar(max); alter table BPAAliveResources drop constraint PK_BPAAliveResources; alter table BPAAliveResources alter column MachineName nvarchar(128) not null; alter table BPAAliveResources add constraint PK_BPAAliveResources primary key clustered (MachineName, UserID); INSERT INTO BPADBVersion VALUES ( ''216'', GETUTCDATE(), ''db_upgradeR216.sql UTC'', ''Increase ArchiveInProgress & MachineName column sizes'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='217') begin exec('create table BPAGroupUser ( groupid uniqueidentifier not null constraint FK_BPAGroupUser_BPAGroup foreign key references BPAGroup(id) on delete cascade, memberid uniqueidentifier not null constraint FK_BPAGroupUser_BPAUser foreign key references BPAUser(userid) on delete cascade, constraint PK_BPAGroupUser primary key clustered (groupid, memberid) ); ')exec('')exec('if not exists(select * from sys.views where name = ''BPVGroupedUsers'') exec (N''create view BPVGroupedUsers as select 1 as placeholder''); ')exec('')exec('alter view BPVGroupedUsers as select g.treeid as treeid, g.id as groupid, g.name as groupname, u.userid as id, isnull(u.username, ''['' + u.systemusername + '']'') as name, case when u.systemusername is not null then 1 else 0 end as issystemuser, u.validfromdate as validfrom, u.validtodate as validto, u.passwordexpirydate as passwordexpiry, u.lastsignedin as lastsignedin, u.isdeleted as isdeleted, u.loginattempts as loginattempts, c.maxloginattempts as maxloginattempts, ura.userroleid as roleid from BPAUser u cross join BPASysConfig c left join ( BPAGroupUser gu inner join BPAGroup g on gu.groupid = g.id ) on gu.memberid = u.userid left join BPAUserRoleAssignment ura on ura.userid = u.userid ')exec('')exec('INSERT INTO BPATree ([id] ,[name]) VALUES (6 ,''users''); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''217'', GETUTCDATE(), ''db_upgrade217.sql UTC'', ''Adds BPAGroupUser and creates associated view;'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='218') begin exec('if not exists(select * from sys.views where name = ''BPVScriptEnvironment'') exec (N''create view BPVScriptEnvironment as select 1 as placeholder''); ')exec('')exec('alter view BPVScriptEnvironment as select isnull(col_length(''BPASysConfig'', ''InstallInProgress''), 0) as InstallInProgress; ')exec('')exec('if (select InstallInProgress from BPVScriptEnvironment) = 1 update BPAKeyStore set name = ''Default Encryption Scheme'' where name = ''Credentials Key''; INSERT INTO BPADBVersion VALUES ( ''218'', GETUTCDATE(), ''db_upgradeR218.sql UTC'', ''Rename Credentials Key to Default Encryption Scheme for new installs'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='219') begin exec('create table BPAScreenshot ( id int not null identity constraint PK_BPAScreenshot primary key, resourceid uniqueidentifier not null, stageid uniqueidentifier not null, processname nvarchar(max) not null, lastupdated datetime not null, timezoneoffset int not null, screenshot nvarchar(max) not null, encryptid int not null constraint FK_BPAScreenshot_BPAKeyStore foreign key references BPAKeyStore (id) ); exec sp_rename ''[BPASysConfig].[encryptid]'', ''defaultencryptid'', ''COLUMN''; declare @id int; insert into BPAPerm (name) values(''View resource screen captures''); select @id = id from BPAPerm where name = ''View resource screen captures''; insert into BPAPermGroupMember (permgroupid, permid) select g.id, @id from BPAPermGroup g where g.name = ''Control Room''; insert into BPAUserRolePerm (userroleid, permid) select r.id, @id from BPAUserRole r where r.name in (''System Administrator'', ''Tester'', ''Process Administrator''); INSERT INTO BPADBVersion VALUES ( ''219'', GETUTCDATE(), ''db_upgradeR219.sql UTC'', ''Add screenshot table and permissions to view screenshots'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='220') begin exec('alter table BPASession add lastupdated datetime null; alter table BPASession add laststage nvarchar(max) null; alter table BPASession add warningthreshold integer null; alter table BPAResource add [userID] uniqueidentifier null; ')exec('')exec('alter view BPVSessionInfo as select s.sessionid as "sessionid", s.sessionnumber as "sessionnumber", s.startdatetime as "startdatetime", s.enddatetime as "enddatetime", s.processid as "processid", p.name as "processname", s.starterresourceid as "starterresourceid", sr.name as "starterresourcename", s.starteruserid as "starteruserid", isnull(su.username, ''['' + su.systemusername + '']'') as "starterusername", s.runningresourceid as "runningresourceid", rr.name as "runningresourcename", s.runningosusername as "runningosusername", s.statusid as "statusid", s.startparamsxml as "startparamsxml", s.logginglevelsxml as "logginglevelsxml", s.sessionstatexml as "sessionstatexml", s.queueid as "queueid", s.lastupdated as "lastupdated", s.laststage as "laststage", s.warningthreshold as "warningthreshold" from BPASession s join BPAProcess p on s.processid = p.processid join BPAResource sr on s.starterresourceid = sr.resourceid join BPAResource rr on s.runningresourceid = rr.resourceid join BPAUser su on s.starteruserid = su.userid where s.statusid <> 6; ')exec('')exec('alter table BPAResource add DisplayStatus as ( case when (AttributeID & 13) <> 0 then null when [status] = ''Offline'' then [status] when DATEDIFF(second, lastupdated, GETUTCDATE()) >= 60 then ''Missing'' when (AttributeID & 16) <> 0 then ''Logged Out'' when (AttributeID & 32) <> 0 then ''Private'' when actionsrunning = 0 then ''Idle'' else ''Working'' end); ')exec('')exec('insert into BPAResourceAttribute (AttributeID, AttributeName) values (16, ''Login Agent''); insert into BPAResourceAttribute (AttributeID, AttributeName) values (32, ''Private''); ')exec('')exec('alter procedure BPDS_WorkforceAvailability as select DisplayStatus as [Status], COUNT(*) as [Total] from BPAResource where DisplayStatus is not null group by DisplayStatus; return; ')exec('')exec('update BPATile set [description]=''Current status of registered resources'', xmlproperties=''<Chart type="6" plotByRow="false"><Procedure name="BPDS_WorkforceAvailability" /></Chart>'' where name=''Workforce Availability'' and xmlproperties like ''%Procedure name="BPDS_WorkforceAvailability"%''; update BPAResource set lastupdated = null INSERT INTO BPADBVersion VALUES ( ''220'', GETUTCDATE(), ''db_upgradeR220.sql UTC'', ''Provides additional resource info and updates Worforce Availability tile'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='221') begin exec('insert into BPAValCheck (checkid, catid, typeid, description, enabled) select 141, c.catid, t.typeid, ''"Pause After Step" not specified in navigate stage'', 1 from BPAValType t cross join BPAValCategory c where t.description = ''Warning'' and c.description = ''Stage Validation''; INSERT INTO BPADBVersion VALUES ( ''221'', GETUTCDATE(), ''db_upgradeR221.sql UTC'', ''Adds warning when "Pause After Step" is not set in nav stage'' ); ') end
if not exists (select 1 from BPADBVersion where dbversion='222') begin exec('alter table BPADBVersion add timezoneoffset int null; ')exec('')exec('update BPADBVersion set timezoneoffset=0, scriptname=replace(scriptname,'' UTC'','''') where scriptname like ''%UTC''; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''222'', GETUTCDATE(), ''db_upgradeR222.sql'', ''Adds timezoneoffset column to BPADBVersion, and removes tempory UTC flag.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='223') begin exec('alter table BPASession add starttimezoneoffset int null, endtimezoneoffset int null, lastupdatedtimezoneoffset int null; exec sp_refreshview ''BPVSession''; ')exec('')exec('alter view BPVSessionInfo as select s.sessionid as "sessionid", s.sessionnumber as "sessionnumber", s.startdatetime as "startdatetime", s.starttimezoneoffset as "starttimezoneoffset", s.enddatetime as "enddatetime", s.endtimezoneoffset as "endtimezoneoffset", s.processid as "processid", p.name as "processname", s.starterresourceid as "starterresourceid", sr.name as "starterresourcename", s.starteruserid as "starteruserid", isnull(su.username, ''['' + su.systemusername + '']'') as "starterusername", s.runningresourceid as "runningresourceid", rr.name as "runningresourcename", s.runningosusername as "runningosusername", s.statusid as "statusid", s.startparamsxml as "startparamsxml", s.logginglevelsxml as "logginglevelsxml", s.sessionstatexml as "sessionstatexml", s.queueid as "queueid", s.lastupdated as "lastupdated", s.lastupdatedtimezoneoffset as "lastupdatedtimezoneoffset", s.laststage as "laststage", s.warningthreshold as "warningthreshold" from BPASession s join BPAProcess p on s.processid = p.processid join BPAResource sr on s.starterresourceid = sr.resourceid join BPAResource rr on s.runningresourceid = rr.resourceid join BPAUser su on s.starteruserid = su.userid where s.statusid <> 6; ')exec('')exec('alter table BPASessionLog_NonUnicode add starttimezoneoffset int null, endtimezoneoffset int null; alter table BPASessionLog_Unicode add starttimezoneoffset int null, endtimezoneoffset int null; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''223'', GETUTCDATE(), ''db_upgradeR223.sql'', ''Adds start/end timezoneoffset columns to BPASession/BPASessionLog tables.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='224') begin exec('update BPAPermGroup set name=''Analytics'' where name=''Dashboard''; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''224'', GETUTCDATE(), ''db_upgradeR224.sql'', ''Renames the Dashboard Role Group to be Analytics'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='225') begin exec('declare @id int; insert into BPAPerm (name) values(''Design Published Dashboards''); select @id = id from BPAPerm where name = ''Design Published Dashboards''; insert into BPAPermGroupMember (permgroupid, permid) select g.id, @id from BPAPermGroup g where g.name = ''Analytics''; insert into BPAUserRolePerm (userroleid, permid) select r.userroleid, @id from BPAUserRolePerm r inner join BPAPerm p on p.id = r.permid where p.name = ''Design Global Dashboards''; INSERT INTO BPADBVersion VALUES ( ''225'', GETUTCDATE(), ''db_upgradeR225.sql'', ''Adds Design Published Dashboards Permission'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='226') begin exec('SET ANSI_NULLS ON ')exec('')exec('SET QUOTED_IDENTIFIER ON ')exec('')exec('if exists (select 1 from sysobjects where id = object_id(''usp_setupDataSource'') and type=''P'') begin drop procedure [usp_setupDataSource] end ')exec('')exec('CREATE procedure usp_setupDataSource @spName nvarchar(128), @grant bit as begin DECLARE @sql nvarchar(200) if not exists(select 1 from sys.objects where type=''P'' and name=@spName) begin SET @sql = ''create procedure '' + quotename(@spName) + '' as begin set nocount on; end''; EXEC sp_executesql @sql if (@grant =1) begin SET @sql = ''grant execute on OBJECT::'' + quotename(@spName) + '' to bpa_ExecuteSP_DataSource_custom''; EXEC sp_executesql @sql end end end ')exec('')exec('grant execute on OBJECT::usp_setupDataSource to bpa_ExecuteSP_System; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''226'', GETUTCDATE(), ''db_upgradeR226.sql'', ''Sql inject protection on tile data source import.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='227') begin exec('delete from BPAAlertEvent where sessionid not in (select sessionid from BPASession); alter table BPACaseLock drop constraint FK_CaseLock_Session; alter table BPACaseLock add constraint FK_CaseLock_Session foreign key(sessionid) references BPASession (sessionid) on Delete Cascade; alter table BPAAlertEvent add constraint FK_AlertEvent_Session foreign key(sessionid) references BPASession (sessionid) on delete cascade; alter table BPAEnvLock drop constraint FK_BPAEnvLock_BPASession; alter table BPAEnvLock add constraint FK_BPAEnvLock_BPASession foreign key(sessionid) references BPASession (sessionid) on delete cascade; INSERT INTO BPADBVersion VALUES ( ''227'', GETUTCDATE(), ''db_upgradeR227.sql'', ''Ensure all children of a BPASession record are cascade deleted when the session is deleted.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='228') begin exec('declare @id int; insert into BPAPerm (name) values(''Import Published Dashboard''); select @id = id from BPAPerm where name = ''Import Published Dashboard''; insert into BPAPermGroupMember (permgroupid, permid) select g.id, @id from BPAPermGroup g where g.name = ''Analytics''; insert into BPAUserRolePerm (userroleid, permid) select r.userroleid, @id from BPAUserRolePerm r inner join BPAPerm p on p.id = r.permid where p.name = ''Import Global Dashboard''; INSERT INTO BPADBVersion VALUES ( ''228'', GETUTCDATE(), ''db_upgradeR228.sql'', ''Adds Import Published Dashboard Permission'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='229') begin exec('ALTER TABLE BPAProcess ADD forceLiteralForm Bit NOT NULL DEFAULT(0); ')exec('')exec('ALTER VIEW BPVGroupedProcessesObjects as select g.treeid as treeid, g.id as groupid, g.name as groupname, p.processid as id, p.name as name, p.ProcessType as processtype, p.description as description, p.createdate as createddate, cu.username as createdby, p.lastmodifieddate as lastmodifieddate, mu.username as lastmodifiedby, p.attributeid as attributes, pl.lockdatetime as lockdatetime, pl.userid as lockuser, pl.machinename as lockmachinename, p.wspublishname as webservicename, p.forceLiteralForm as forceDocumentLiteral from BPAProcess p join BPAUser cu on p.createdby = cu.userid join BPAUser mu on p.lastmodifiedby = mu.userid left join ( BPAGroupProcess gp inner join BPAGroup g on gp.groupid = g.id ) on gp.processid = p.processid left join BPAProcessLock pl on pl.processid = p.processid; ')exec('')exec('exec sp_refreshview ''BPVGroupedProcesses''; exec sp_refreshview ''BPVGroupedObjects''; INSERT INTO BPADBVersion VALUES ( ''229'', GETUTCDATE(), ''db_upgradeR229.sql'', ''Adds Import Published Dashboard Permission'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='230') begin exec('ALTER TABLE BPAProcess ADD useLegacyNamespace Bit NOT NULL DEFAULT(1); ')exec('')exec('ALTER VIEW BPVGroupedProcessesObjects as select g.treeid as treeid, g.id as groupid, g.name as groupname, p.processid as id, p.name as name, p.ProcessType as processtype, p.description as description, p.createdate as createddate, cu.username as createdby, p.lastmodifieddate as lastmodifieddate, mu.username as lastmodifiedby, p.attributeid as attributes, pl.lockdatetime as lockdatetime, pl.userid as lockuser, pl.machinename as lockmachinename, p.wspublishname as webservicename, p.forceLiteralForm as forceDocumentLiteral, p.useLegacyNamespace as useLegacyNamespace from BPAProcess p join BPAUser cu on p.createdby = cu.userid join BPAUser mu on p.lastmodifiedby = mu.userid left join ( BPAGroupProcess gp inner join BPAGroup g on gp.groupid = g.id ) on gp.processid = p.processid left join BPAProcessLock pl on pl.processid = p.processid; ')exec('')exec('exec sp_refreshview ''BPVGroupedProcesses''; exec sp_refreshview ''BPVGroupedObjects''; INSERT INTO BPADBVersion VALUES ( ''230'', GETUTCDATE(), ''db_upgradeR230.sql'', ''Added field to state if a legacy namespace should be used.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='231') begin exec('INSERT INTO BPAValCheck ([checkid] ,[catid] ,[typeid] ,[description] ,[enabled]) VALUES (142 ,0 ,2 ,''Exception Type ''''{0}'''' not previously defined within the environment'' ,0) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''231'', GETUTCDATE(), ''db_upgradeR231.sql UTC'', ''Adds additional process validation check for exception stage types'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='232') begin exec('SET ANSI_NULLS ON ')exec('')exec('SET QUOTED_IDENTIFIER ON ')exec('')exec('ALTER procedure usp_getnextcase @queuename nvarchar(255), @keyfilter nvarchar(255) = null, @sess uniqueidentifier = null, @ontag1 nvarchar(255) = null, @ontag2 nvarchar(255) = null, @ontag3 nvarchar(255) = null, @ontag4 nvarchar(255) = null, @ontag5 nvarchar(255) = null, @ontag6 nvarchar(255) = null, @ontag7 nvarchar(255) = null, @ontag8 nvarchar(255) = null, @ontag9 nvarchar(255) = null, @offtag1 nvarchar(255) = null, @offtag2 nvarchar(255) = null, @offtag3 nvarchar(255) = null, @offtag4 nvarchar(255) = null, @offtag5 nvarchar(255) = null, @offtag6 nvarchar(255) = null, @offtag7 nvarchar(255) = null, @offtag8 nvarchar(255) = null, @offtag9 nvarchar(255) = null as declare @sql nvarchar(max); declare @params nvarchar(max); declare @lockid uniqueidentifier; set @lockid = newid(); if object_id(''tempdb..#ontags'') is not null drop table #ontags; if object_id(''tempdb..#offtags'')is not null drop table #offtags; create table #ontags (id int); create table #offtags (id int); if @ontag1 is not null and @ontag1 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag1; if @ontag2 is not null and @ontag2 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag2; if @ontag3 is not null and @ontag3 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag3; if @ontag4 is not null and @ontag4 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag4; if @ontag5 is not null and @ontag5 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag5; if @ontag6 is not null and @ontag6 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag6; if @ontag7 is not null and @ontag7 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag7; if @ontag8 is not null and @ontag8 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag8; if @ontag9 is not null and @ontag9 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag9; if exists (select 1 from #ontags where id is null) return; if @offtag1 is not null insert into #offtags exec usp_gettagids @tag=@offtag1; if @offtag2 is not null insert into #offtags exec usp_gettagids @tag=@offtag2; if @offtag3 is not null insert into #offtags exec usp_gettagids @tag=@offtag3; if @offtag4 is not null insert into #offtags exec usp_gettagids @tag=@offtag4; if @offtag5 is not null insert into #offtags exec usp_gettagids @tag=@offtag5; if @offtag6 is not null insert into #offtags exec usp_gettagids @tag=@offtag6; if @offtag7 is not null insert into #offtags exec usp_gettagids @tag=@offtag7; if @offtag8 is not null insert into #offtags exec usp_gettagids @tag=@offtag8; if @offtag9 is not null insert into #offtags exec usp_gettagids @tag=@offtag9; delete from #offtags where id is null; set @sql = '' set transaction isolation level read uncommitted; insert into BPACaseLock (id,locktime,sessionid,lockid) select top 1 i.ident ,getutcdate() ,case when @sess is null then i.sessionid else @sess end ,@lockid from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident left join BPACaseLock l on l.id = i.ident where q.name = @queuename and q.running = 1 and i.finished is null and (i.deferred is null or i.deferred < getutcdate()) and l.id is null ''; if @keyfilter is not null begin SET @sql = @sql + '' and i.keyvalue = @keyfilter''; end if exists (select 1 from #ontags) begin set @sql = @sql + '' and ( select count(*) from BPAWorkQueueItemTag it join #ontags ot on it.tagid = ot.id where it.queueitemident = i.ident ) = (select count(*) from #ontags) ''; end declare @onwildcardsql nvarchar(max) set @onwildcardsql = '' and exists ( select 1 from BPAWorkQueueItemTag it join BPATag t on it.tagid = t.id where it.queueitemident = i.ident and t.tag like @ontag''; if @ontag1 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''1)''; if @ontag2 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''2)''; if @ontag3 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''3)''; if @ontag4 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''4)''; if @ontag5 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''5)''; if @ontag6 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''6)''; if @ontag7 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''7)''; if @ontag8 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''8)''; if @ontag9 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''9)''; if exists (select 1 from #offtags) begin set @sql = @sql + '' and not exists ( select 1 from BPAWorkQueueItemTag it join #offtags ot on it.tagid = ot.id where it.queueitemident = i.ident ) ''; end set @sql = @sql + '' order by i.priority, i.loaded, i.ident; ''; set @params = '' @sess uniqueidentifier, @queuename nvarchar(255), @keyfilter nvarchar(255), @lockid uniqueidentifier, @ontag1 nvarchar(255), @ontag2 nvarchar(255), @ontag3 nvarchar(255), @ontag4 nvarchar(255), @ontag5 nvarchar(255), @ontag6 nvarchar(255), @ontag7 nvarchar(255), @ontag8 nvarchar(255), @ontag9 nvarchar(255) ''; declare @attempt int, @maxattempts int; set @maxattempts = 100; set @attempt = 1; while @attempt <= @maxattempts begin begin try exec sp_executesql @sql,@params,@sess=@sess,@queuename=@queuename,@keyfilter=@keyfilter,@lockid=@lockid,@ontag1=@ontag1,@ontag2=@ontag2,@ontag3=@ontag3,@ontag4=@ontag4,@ontag5=@ontag5,@ontag6=@ontag6,@ontag7=@ontag7,@ontag8=@ontag8,@ontag9=@ontag9; break; end try begin catch if error_number() = 2627 begin set @attempt = @attempt + 1; if @attempt <= @maxattempts continue; end; exec usp_rethrow; return; end catch end; select i.encryptid, i.id, i.ident, i.keyvalue, i.data, i.status, i.attempt from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident join BPACaseLock l on i.ident = l.id where l.lockid = @lockid; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''232'', GETUTCDATE(), ''db_upgradeR232.sql UTC'', ''usp_getnextcase stored procedure optimisation'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='233') begin exec('insert into BPATileDataSources (spname, tiletype, helppage) values (''BPDS_I_LicenseInformation'', 1, ''LicenseInformation.htm''); insert into BPATile (id, name, tiletype, description, autorefresh, xmlproperties) values(newid(),''License Information'',1,''Information about limits and usage based on the active license'',0,''<Chart type="3" plotByRow="false"><Procedure name="BPDS_I_LicenseInformation" /></Chart>''); INSERT INTO BPADBVersion VALUES ( ''233'', GETUTCDATE(), ''db_upgradeR233.sql UTC'', ''Add an internal tile datasource for license info'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='234') begin exec('declare @currentSchema nvarchar(128) select @currentSchema = SCHEMA_NAME() if @currentSchema <> ''dbo'' begin if exists (select 1 from sysobjects where id = OBJECT_ID(''dbo.usp_setupDataSource'') and ''dbo'' = OBJECT_SCHEMA_NAME(id) and type=''P'') begin declare @sql nvarchar(200) set @sql = ''ALTER SCHEMA '' + @currentSchema + '' TRANSFER dbo.usp_setupDataSource'' exec sp_executesql @sql end end insert into BPADBVersion values ( ''234'', GETUTCDATE(), ''db_upgradeR234.sql'', ''Change schema of usp_setupDataSource procedure from dbo to current if different.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='235') begin exec('create table BPAGroupUserRolePerm ( groupid uniqueidentifier not null constraint FK_BPAGroupUserRolePerm_BPAGroup foreign key references BPAGroup(id) on delete cascade, userroleid int not null constraint FK_BPAGroupUserRolePerm_BPAUserRole foreign key references BPAUserRole(id), permid int not null constraint FK_BPAGroupUserRolePerm_BPAPerm foreign key references BPAPerm(id), constraint PK_BPAGroupUserRolePerm primary key clustered (groupid, userroleid, permid), constraint FK_BPAGroupUserRolePerm_BPAUserRolePerm foreign key (permid, userroleid) references BPAUserRolePerm(permid, userroleid) on delete cascade); alter table BPAGroup add isrestricted bit not null default 0; alter table BPAPerm add treeid int null; ')exec('')exec('update BPAPerm set treeid=(select id from BPATree where name=''Objects'') where name in ( ''Create/Clone Business Object'', ''Delete Business Object'', ''Edit Business Object'', ''Export Business Object'', ''Import Business Object'', ''Test Business Object'', ''View Business Object'', ''Edit Object Groups''); update BPAPerm set treeid=(select id from BPATree where name=''Processes'') where name in ( ''Create/Clone Process'', ''Delete Process'', ''Edit Process'', ''Export Process'', ''Import Process'', ''Test Process'', ''View Process'', ''Edit Process Groups''); declare @id int; insert into BPAPerm (name, treeid) select ''Manage Process Access Rights'', id from BPATree where name=''Processes''; insert into BPAPerm (name, treeid) select ''Manage Business Object Access Rights'', id from BPATree where name=''Objects''; select @id = id from BPAPermGroup where name=''Process Studio''; insert into BPAPermGroupMember (permgroupid, permid) select @id, a.id from BPAPerm a where a.name = ''Manage Process Access Rights''; select @id = id from BPAPermGroup where name=''Object Studio''; insert into BPAPermGroupMember (permgroupid, permid) select @id, a.id from BPAPerm a where a.name = ''Manage Business Object Access Rights''; select @id = id from BPAUserRole where name=''System Administrator''; insert into BPAUserRolePerm (userroleid, permid) select @id, a.id from BPAPerm a where a.name in (''Manage Process Access Rights'', ''Manage Business Object Access Rights''); ')exec('')exec('update BPAUserRole set name = name + ''s'' where name in ( ''Alert Subscriber'', ''Developer'', ''Process Administrator'', ''Runtime Resource'', ''Schedule Manager'', ''System Administrator'', ''Tester''); ')exec('')exec('update BPAPerm set name = ''Create Business Object'' where name = ''Create/Clone Business Object''; update BPAPerm set name = ''Create Process'' where name = ''Create/Clone Process''; update BPAPerm set name = ''Execute Business Object'' where name = ''Test Business Object''; update BPAPerm set name = ''Execute Process'' where name = ''Test Process''; ')exec('')exec('delete from BPAPermGroupMember where permid in (select id from BPAPerm where name in (''Compare Business Objects'', ''Compare Processes'')); delete from BPAUserRolePerm where permid in (select id from BPAPerm where name in (''Compare Business Objects'', ''Compare Processes'')); delete from BPAPerm where name = ''Compare Business Objects'' delete from BPAPerm where name = ''Compare Processes'' ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''235'', GETUTCDATE(), ''db_upgradeR235.sql'', ''Add database structure for segregated permissions and add "Manage Access Rights" permissions.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='236') begin exec('update BPAPerm set [name] = ''View Process Definition'' where [name] = ''View Process''; update BPAPerm set [name] = ''View Business Object Definition'' where [name] = ''View Business Object'' INSERT INTO BPADBVersion VALUES ( ''236'', GETUTCDATE(), ''db_upgradeR236.sql'', ''Renames view process permissions'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='237') begin exec('create table BPATreePerm ( id int identity(1,1) not null, treeid int not null constraint FK_BPATreePerm_BPATree foreign key references BPATree(id) on delete cascade, permid int not null constraint FK_BPATreePerm_BPAPerm foreign key references BPAPerm(id), groupLevelPerm tinyint not null); insert into BPATreePerm (treeid, permid, groupLevelPerm) select 2, id, 0 from BPAPerm where name in ( ''Delete Process'', ''Edit Process'', ''Export Process'', ''Execute Process'', ''View Process Definition''); insert into BPATreePerm (treeid, permid, groupLevelPerm) select 2, id, 1 from BPAPerm where name in ( ''Create Process'', ''Import Process'', ''Edit Process Groups'', ''Manage Process Access Rights''); insert into BPATreePerm (treeid, permid, groupLevelPerm) select 3, id, 0 from BPAPerm where name in ( ''Delete Business Object'', ''Edit Business Object'', ''Export Business Object'', ''Execute Business Object'', ''View Business Object Definition''); insert into BPATreePerm (treeid, permid, groupLevelPerm) select 3, id, 1 from BPAPerm where name in ( ''Create Business Object'', ''Import Business Object'', ''Edit Object Groups'', ''Manage Business Object Access Rights''); INSERT INTO BPADBVersion VALUES ( ''237'', GETUTCDATE(), ''db_upgradeR237.sql'', ''Adds a new BPATreePerm table which maps permissions to tree types'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='238') begin exec('declare @userRoleId int = ( select top 1 [id] from [BPAUserRole] where [name] = ''Runtime Resources''); declare @permissionId int = ( select top 1 [id] from [BPAPerm] where [name] = ''Execute Process''); if not exists (select * from [BPAUserRolePerm] where userroleid = @userRoleId and permid = @permissionId) begin insert into [BPAUserRolePerm] (userroleid, permid) values (@userRoleId, @permissionId) end insert into BPADBVersion values ( ''238'', GETUTCDATE(), ''db_upgradeR238.sql'', ''Adds the execute process permission to the runtime resources user role.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='239') begin exec('create table BPATreeDefaultGroup ( id int identity(1,1) not null, treeid int not null constraint FK_BPATreeDefaultGroup_BPATree foreign key references BPATree(id) on delete cascade, groupid uniqueidentifier not null constraint FK_BPATreeDefaultGroup_BPAGroup foreign key references BPAGroup(id) on delete cascade, constraint UNIQUE_BPATreeDefaultGroup_TreeID unique(treeid) ); declare @processTreeDefaultGroupId uniqueidentifier = NEWID() declare @objectTreeDefaultGroupId uniqueidentifier = NEWID() declare @resourceTreeDefaultGroupId uniqueidentifier = NEWID() declare @newdefaultnameprocesstree nvarchar (12) = ''Default'' declare @newdefaultnameobjecttree nvarchar (12) = ''Default'' declare @newdefaultnameresourcetree nvarchar (12) = ''Default'' declare @defaultcounter int = 1 while exists (select id from BPAGroup where [name] = @newdefaultnameprocesstree and treeid = 2) begin set @newdefaultnameprocesstree = concat(''Default ('', @defaultcounter, '')'') set @defaultcounter = @defaultcounter + 1 end set @defaultcounter = 1 while exists (select id from BPAGroup where [name] = @newdefaultnameobjecttree and treeid = 3) begin set @newdefaultnameobjecttree = concat(''Default ('', @defaultcounter, '')'') set @defaultcounter = @defaultcounter + 1 end set @defaultcounter = 1 while exists (select id from BPAGroup where [name] = @newdefaultnameresourcetree and treeid = 5) begin set @newdefaultnameresourcetree = concat(''Default ('', @defaultcounter, '')'') set @defaultcounter = @defaultcounter + 1 end insert into BPAGroup (id, treeid, [name], isrestricted) values (@processTreeDefaultGroupId, 2, @newdefaultnameprocesstree, 0), (@objectTreeDefaultGroupId, 3, @newdefaultnameobjecttree, 0), (@resourceTreeDefaultGroupId, 5, @newdefaultnameresourcetree, 0); insert into BPATreeDefaultGroup (treeid, groupid) values (2, @processTreeDefaultGroupId), (3, @objectTreeDefaultGroupId), (5, @resourceTreeDefaultGroupId); insert into BPAGroupProcess(groupid, processid) select @processTreeDefaultGroupID, p.processid from BPAProcess p left join BPAGroupProcess gp on p.processid = gp.processid where groupid is null and p.ProcessType = ''P'' insert into BPAGroupProcess(groupid, processid) select @objectTreeDefaultGroupID, p.processid from BPAProcess p left join BPAGroupProcess gp on p.processid = gp.processid where groupid is null and p.ProcessType = ''O'' insert into BPAGroupResource(groupid, memberid) select @resourceTreeDefaultGroupId, r.resourceid from BPAResource r left join BPAGroupResource gr on r.resourceid = gr.memberid where groupid is null insert into BPADBVersion values ( ''239'', GETUTCDATE(), ''db_upgradeR239.sql'', ''Adds the BPATreeDefaultGroup table which maps default groups to trees. Adds default groups for the process, object and resource trees.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='240') begin exec('alter view BPVGroupedProcessesObjects as select g.treeid as treeid, g.id as groupid, g.name as groupname, p.processid as id, p.name as name, p.ProcessType as processtype, p.description as description, p.createdate as createddate, cu.username as createdby, p.lastmodifieddate as lastmodifieddate, mu.username as lastmodifiedby, p.attributeid as attributes, pl.lockdatetime as lockdatetime, pl.userid as lockuser, pl.machinename as lockmachinename, p.wspublishname as webservicename, p.forceLiteralForm as forceDocumentLiteral, p.useLegacyNamespace as useLegacyNamespace, p.sharedObject as sharedObject from BPAProcess p join BPAUser cu on p.createdby = cu.userid join BPAUser mu on p.lastmodifiedby = mu.userid left join ( BPAGroupProcess gp inner join BPAGroup g on gp.groupid = g.id ) on gp.processid = p.processid left join BPAProcessLock pl on pl.processid = p.processid; ')exec('')exec('exec sp_refreshview ''BPVGroupedProcesses''; exec sp_refreshview ''BPVGroupedObjects''; INSERT INTO BPADBVersion VALUES ( ''240'', GETUTCDATE(), ''db_upgradeR240.sql'', ''Add Shared Object flag to Grouped Object/Process View'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='241') begin exec('delete from BPAGroupProcess where processid in (select processid from BPAProcess where AttributeId & 1 = 1); delete from BPAGroupResource where memberid in (select resourceid from BPAResource where AttributeID & 1 = 1); ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''241'', GETUTCDATE(), ''db_upgradeR241.sql'', ''Remove existing retired processes / objects /resources from groups'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='242') begin exec('delete from BPAGroupUser where memberid in (select userid from BPAUser where isdeleted = 1) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''242'', GETUTCDATE(), ''db_upgradeR242.sql'', ''Remove existing deleted users from groups'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='243') begin exec('insert into BPAValCheck (checkid, catid, typeid, [description], [enabled]) values (143, 0, 1, ''Stage has a direct or indirect reference to Processes or Objects which may contain references to items that the user does not have permission to use. Execution may fail for this user: {0}'', 1) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''243'', GETUTCDATE(), ''db_upgradeR243.sql'', ''Add new validation checks for processes dependencies the user cannot access.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='244') begin exec('alter view BPVGroupedResources as select g.treeid as treeid, case when r.pool is not null then r.pool else g.id end as groupid, g.name as groupname, r.resourceid as id, r.name as name, r.attributeid as attributes, case when r.pool is not null then 1 else 0 end as ispoolmember, r.status as status from BPAResource r left join ( BPAGroupResource gr inner join BPAGroup g on gr.groupid = g.id ) on gr.memberid = r.resourceid; ')exec('')exec('declare @treeid int; select @treeid=id from BPATree where name=''Resources''; insert into BPAPerm (name, treeid) values (''Authenticate as Resource'', null); insert into BPAPerm (name, treeid) values (''Manage Resource Access Rights'', @treeid); insert into BPAPerm (name, treeid) values (''Edit Resource Groups'', @treeid); update BPAPerm set name=''Configure Resource'', treeid=@treeid where name=''Resources - Management''; update BPAPerm set name=''View Resource'', treeid=@treeid where name=''Read Access to Session Management''; update BPAPerm set name=''Control Resource'', treeid=@treeid where name=''Full Access to Session Management''; update BPAPerm set name=''View Resource Screen Captures'', treeid=@treeid where name=''View resource screen captures''; declare @groupid int; insert into BPAPermGroup (name) values (''Resources''); select @groupid=id from BPAPermGroup where name=''Resources''; insert into BPAPermGroupMember (permgroupid, permid) select @groupid, id from BPAPerm where name=''Authenticate as Resource''; insert into BPAPermGroupMember (permgroupid, permid) select @groupid, id from BPAPerm where name=''Manage Resource Access Rights''; insert into BPAPermGroupMember (permgroupid, permid) select @groupid, id from BPAPerm where name=''Edit Resource Groups''; update BPAPermGroupMember set permgroupid=@groupid where permid in ( select id from BPAPerm where name in (''View Resource'', ''Configure Resource'', ''Control Resource'', ''View Resource Screen Captures'')); insert into BPATreePerm (treeid, permid, groupLevelPerm) select @treeid, id, 0 from BPAPerm where name=''View Resource''; insert into BPATreePerm (treeid, permid, groupLevelPerm) select @treeid, id, 0 from BPAPerm where name=''Configure Resource''; insert into BPATreePerm (treeid, permid, groupLevelPerm) select @treeid, id, 0 from BPAPerm where name=''Control Resource''; insert into BPATreePerm (treeid, permid, groupLevelPerm) select @treeid, id, 1 from BPAPerm where name=''Manage Resource Access Rights''; insert into BPATreePerm (treeid, permid, groupLevelPerm) select @treeid, id, 0 from BPAPerm where name=''View Resource Screen Captures''; insert into BPATreePerm (treeid, permid, groupLevelPerm) select @treeid, id, 1 from BPAPerm where name=''Edit Resource Groups''; declare @id int; select @id = id from BPAUserRole where name=''System Administrators''; insert into BPAUserRolePerm (userroleid, permid) select @id, a.id from BPAPerm a where a.name in (''Authenticate as Resource'', ''Manage Resource Access Rights''); select @id = id from BPAUserRole where name=''Runtime Resources''; insert into BPAUserRolePerm (userroleid, permid) select @id, a.id from BPAPerm a where a.name = ''Authenticate as Resource''; select @id = id from BPAPerm where name=''Edit Resource Groups''; insert into BPAUserRolePerm (userroleid, permid) select rp.userroleid, @id from BPAUserRolePerm rp inner join BPAPerm p on p.id=rp.permid where p.name=''Configure Resource'' drop table BPAResourceRole; INSERT INTO BPADBVersion VALUES ( ''244'', GETUTCDATE(), ''db_upgradeR244.sql'', ''Add resource related group based permissions'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='245') begin exec('alter view BPVGroupedResources as select g.treeid as treeid, (case when r.pool is not null then r.pool else g.id end) as groupid, g.name as groupname, r.resourceid as id, r.name as name, r.attributeid as attributes, case when r.pool is not null then 1 else 0 end as ispoolmember, ''Idle'' as status from BPAResource r left join ( BPAGroupResource gr inner join BPAGroup g on gr.groupid = g.id ) on gr.memberid = r.resourceid where attributeId & 8 = 0; ')exec('')exec('if not exists(select * from sys.views where name = ''BPVPools'') exec (N''create view BPVPools as select 1 as placeholder''); ')exec('')exec('alter view BPVPools as select g.treeid as treeid, g.id as groupid, g.name as groupname, r.resourceid as id, r.name as name, r.attributeid as attributes, r.status as status from BPAResource r left join ( BPAGroupResource gr inner join BPAGroup g on gr.groupid = g.id ) on gr.memberid = r.resourceid where attributeId & 8 = 8; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''245'', GETUTCDATE(), ''db_upgradeR245.sql'', ''Add pools to resource managment screen'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='246') begin exec('declare @id int; select @id = id from BPAUserRole where name=''Runtime Resources''; insert into BPAUserRolePerm (userroleid, permid) select @id, a.id from BPAPerm a where a.name = ''Processes - View Environment Variables'' or a.name = ''Business Objects - View Environment Variables''; INSERT INTO BPADBVersion VALUES ( ''246'', GETUTCDATE(), ''db_upgradeR246.sql'', ''Add view environment variables permissions to Runtime Resources role'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='247') begin exec('if (select InstallInProgress from BPVScriptEnvironment) <> 1 begin declare @permissionId int select top 1 @permissionId = [id] from [BPAPerm] where [name] = ''Authenticate as Resource'' declare @userRoleIds table (userRoleId int) insert into @userRoleIds select [userroleid] from [BPAUserRolePerm] except select [userroleid] from [BPAUserRolePerm] where [permid] = @permissionId insert into [BPAUserRolePerm] ([userroleid], [permid]) select [userRoleId], @permissionId from @userRoleIds end INSERT INTO BPADBVersion VALUES ( ''247'', GETUTCDATE(), ''db_upgradeR247.sql'', ''Add "Authenticate as Resource" permission to all existing roles'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='248') begin exec('insert into BPAUserRolePerm (userroleid, permid) select r.id, p.id from BPAUserRole r cross join BPAPerm p where r.name=''Process Administrators'' and p.name in (''Execute Process'',''Execute Business Object'') and not exists (select * from BPAUserRolePerm where r.id = userroleid and p.id = permid); INSERT INTO BPADBVersion VALUES ( ''248'', GETUTCDATE(), ''db_upgradeR248.sql'', ''Add execute process/business object to process administrators'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='249') begin exec('alter table BPAAuditEvents alter column comments nvarchar(MAX) null INSERT INTO BPADBVersion VALUES ( ''249'', GETUTCDATE(), ''db_upgradeR249.sql'', ''Remove restriction on audit events comment'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='250') begin exec('create procedure #usp_addPermission @permissionname nvarchar(250), @treeparentname nvarchar(100), @groupname nvarchar(100), @roleid int as begin declare @permissionidtable table (id int) insert into [BPAPerm] ([name], [treeid]) output inserted.[id] into @permissionidtable values (@permissionname, null) declare @permissionid int select top 1 @permissionid = [id] from @permissionidtable declare @groupid int select top 1 @groupid = [id] from [BPAPermGroup] where [name] = @groupname insert into [BPAPermGroupMember] ([permgroupid], [permid]) values (@groupid, @permissionid) declare @treeid int select @treeid = [id] from [BPATree] where [name] = @treeparentname insert into [BPATreePerm] (treeid, permid, groupLevelPerm) values (@treeid, @permissionid, 0) insert into [BPAUserRolePerm] ([userroleid], [permid]) values (@roleid, @permissionid) if (select InstallInProgress from BPVScriptEnvironment) <> 1 begin declare @userroleids table (userroleid int) insert into @userroleids select [userroleid] from [BPAUserRolePerm] except select [userroleid] from [BPAUserRolePerm] where [permid] = @permissionid insert into [BPAUserRolePerm] ([userroleid], [permid]) select [userroleid], @permissionid from @userroleids end declare @sysadminroleid int select top 1 @sysadminroleid = [id] from [BPAUserRole] where [name] = ''System Administrators'' delete from [BPAUserRolePerm] where [userroleid] = @sysadminroleid and [permid] = @permissionid insert into [BPAUserRolePerm] ([userroleid], [permid]) values (@sysadminroleid, @permissionid) end ')exec('')exec('declare @rolename nvarchar(max); set @rolename = ''Web Service Consumer''; declare @newname nvarchar(max); set @newname = @rolename declare @suffix nvarchar(max); set @suffix = '' (previousx)''; declare @id int; set @id = 0; while exists (select 1 from BPAUserRole where [name] = @newname) begin set @newname = @rolename + REPLACE(@suffix, ''x'', case when @id = 0 then '''' else cast(@id as nvarchar(10)) end); set @id += 1; end if @newname <> @rolename update BPAUserRole set [name] = @newname where [name] = @rolename; declare @roleidtable table([id] int) insert into BPAUserRole ([name]) output inserted.id into @roleidtable values (@rolename); declare @webserviceroleid int select top 1 @webserviceroleid = [id] from @roleidtable exec #usp_addPermission ''Execute Process as Web Service'', ''Processes'', ''Process Studio'', @webserviceroleid exec #usp_addPermission ''Execute Business Object as Web Service'', ''Objects'', ''Object Studio'', @webserviceroleid insert into BPADBVersion values ( ''250'', getutcdate(), ''db_upgradeR250.sql'', ''Add new permission for executing a process as a web service'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='251') begin exec('alter view BPVGroupedResources as select g.treeid, (case when r.pool is not null then r.pool else g.id end) as groupid, g.name as groupname, r.resourceid as id, r.name, r.AttributeID AS attributes, case when r.pool is not null then 1 else 0 end as ispoolmember, r.status from BPAResource as r left outer join BPAGroupResource as gr inner join BPAGroup as g on gr.groupid = g.id on gr.memberid = r.resourceid ')exec('')exec('insert into BPADBVersion values ( ''251'', getutcdate(), ''db_upgradeR251.sql'', ''Amend BPVGroupedResources to return resource pools in groups'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='252') begin exec('alter table BPAInternalAuth add ProcessId uniqueidentifier, IsWebService bit not null default 0; alter table BPAInternalAuth add constraint FK_BPAInternalAuth_BPAProcess foreign key (ProcessId) references BPAProcess(ProcessId); insert into BPADBVersion values ( ''252'', getutcdate(), ''db_upgradeR252.sql'', ''Add processId column to the internal auth table.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='253') begin exec('CREATE TABLE [BPACacheETags]( [key] [nvarchar](50) NOT NULL, [tag] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_BPACacheETags] PRIMARY KEY CLUSTERED ( [key] ASC ) ) ')exec('')exec('CREATE PROCEDURE [usp_GetCacheETag] @cacheKey NVARCHAR(50) AS BEGIN SET NOCOUNT ON; SELECT TOP 1 T.[tag] FROM ( SELECT TOP 1 [tag], 1 AS [priority] FROM [BPACacheETags] (NOWAIT) WHERE [key] = @cacheKey UNION ALL (SELECT ''00000000-0000-0000-0000-000000000000'' as [tag], 0 AS [priority])) T ORDER BY T.[priority] DESC END ')exec('')exec('CREATE PROCEDURE [usp_SetCacheETag] @cacheKey NVARCHAR(50), @tag UNIQUEIDENTIFIER AS BEGIN SET NOCOUNT ON; IF NOT EXISTS (SELECT * FROM BPACacheETags WHERE [key] = @cacheKey) INSERT INTO BPACacheETags ([key], [tag]) VALUES (@cacheKey, @tag) ELSE UPDATE BPACacheETags SET [tag] = @tag WHERE [key] = @cacheKey END ')exec('')exec('insert into BPADBVersion values ( ''253'', getutcdate(), ''db_upgradeR253.sql'', ''Add caching tables'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='254') begin exec('if (select InstallInProgress from BPVScriptEnvironment) <> 1 begin declare @permissionId int select top 1 @permissionId = [id] from [BPAPerm] where [name] = ''Execute Business Object'' declare @webServiceConsumerId int select top 1 @webServiceConsumerId = [id] from [BPAUserRole] where [name] = ''Web Service Consumer'' declare @userRoleIds table (userRoleId int) insert into @userRoleIds select [userroleid] from [BPAUserRolePerm] where [userroleid] <> @webServiceConsumerId except select [userroleid] from [BPAUserRolePerm] where [permid] = @permissionId insert into [BPAUserRolePerm] ([userroleid], [permid]) select [userRoleId], @permissionId from @userRoleIds end ')exec('')exec('if (select InstallInProgress from BPVScriptEnvironment) <> 1 begin declare @permissionId int select top 1 @permissionId = [id] from [BPAPerm] where [name] = ''Execute Process'' declare @webServiceConsumerId int select top 1 @webServiceConsumerId = [id] from [BPAUserRole] where [name] = ''Web Service Consumer'' declare @userRoleIds table (userRoleId int) insert into @userRoleIds select [userroleid] from [BPAUserRolePerm] where [userroleid] <> @webServiceConsumerId except select [userroleid] from [BPAUserRolePerm] where [permid] = @permissionId insert into [BPAUserRolePerm] ([userroleid], [permid]) select [userRoleId], @permissionId from @userRoleIds end ')exec('')exec('insert into BPADBVersion values ( ''254'', getutcdate(), ''db_upgradeR254.sql'', ''Grant Execute to existing user roles'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='255') begin exec('declare @userRoleId int = ( select top 1 [id] from [BPAUserRole] where [name] = ''Runtime Resources''); declare @permissionId int = ( select top 1 [id] from [BPAPerm] where [name] = ''Execute Business Object''); if not exists (select * from [BPAUserRolePerm] where userroleid = @userRoleId and permid = @permissionId) begin insert into [BPAUserRolePerm] (userroleid, permid) values (@userRoleId, @permissionId) end insert into BPADBVersion values ( ''255'', GETUTCDATE(), ''db_upgradeR255.sql'', ''Adds the execute business object permission to the runtime resources user role.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='256') begin exec('declare @OldSoapPermName as nvarchar(50) ,@NewSoapPermName as nvarchar(50) ,@WebApiPermName as nvarchar(50) ,@WebApiPermId as int; set @OldSoapPermName = N''Business Objects - Web Services''; set @NewSoapPermName = N''Business Objects - SOAP Web Services''; set @WebApiPermName = N''Business Objects - Web API Services''; update BPAPerm set name = @NewSoapPermName where name = @OldSoapPermName; insert into BPAPerm (name) values (@WebApiPermName); set @WebApiPermId = scope_identity(); insert into BPAUserRolePerm (userroleid, permid) select urp.userroleid ,@WebApiPermId from BPAUserRolePerm urp join BPAPerm p on urp.permid = p.id where p.name = @NewSoapPermName; insert into BPAPermGroupMember (permgroupid, permid) select pgm.permgroupid ,@WebApiPermId from BPAPermGroupMember pgm join BPAPerm p on pgm.permid = p.id where p.name = @NewSoapPermName; create table BPAWebApiService ( serviceid uniqueidentifier not null constraint PK_BPAWebApiService primary key, name nvarchar(128) null constraint UNQ_BPAWebApiService_name unique, enabled bit not null, lastupdated datetime not null, baseurl nvarchar(max) null, authenticationtype int not null, authenticationconfig nvarchar(max) not null, commoncodeproperties nvarchar(max) not null default '''', httpRequestConnectionTimeout int not null default 10, authServerRequestConnectionTimeout int not null default 10 ); create table BPAWebApiAction ( actionid int identity not null constraint PK_BPAWebApiAction primary key, serviceid uniqueidentifier not null constraint FK_BPAWebApiAction_BPAWebApiService foreign key references BPAWebApiService (serviceid), name nvarchar(255) not null, description nvarchar(max) null, enabled bit not null, requesthttpmethod nvarchar(50) not null, requesturlpath nvarchar(max) null, requestbodytypeid int not null, requestbodycontent nvarchar(max), enableRequestOutputParameter bit not null, disableSendingOfRequest bit not null, constraint UNQ_BPAWebApiAction_serviceid_name unique (serviceid, name) ); create index Index_BPAWebApiAction_serviced on BPAWebApiAction(serviceid); create table BPAWebApiHeader ( headerid int identity not null constraint PK_BPAWebApiHeader primary key, serviceid uniqueidentifier null constraint FK_BPAWebApiHeader_BPAWebApiService foreign key references BPAWebApiService (serviceid), actionid int null constraint FK_BPAWebApiHeader_BPAWebApiAction foreign key references BPAWebApiAction (actionid), name nvarchar(max) not null, value nvarchar(max) null ); create index Index_BPAWebApiHeader_serviceid on BPAWebApiHeader(serviceid); create index Index_BPAWebApiHeader_actionid on BPAWebApiHeader(actionid); create table BPAWebApiParameter ( parameterid int not null identity constraint PK_BPAWebApiParameter primary key, serviceid uniqueidentifier null constraint FK_BPAWebApiParameter_BPAWebApiService foreign key references BPAWebApiService (serviceid), actionid int null constraint FK_BPAWebApiParameter_BPAWebApiAction foreign key references BPAWebApiAction (actionid), name nvarchar(255) not null, description nvarchar(max) not null, exposetoprocess bit not null, datatype nvarchar(16) not null, initvalue nvarchar(max) null, constraint UNQ_BPAWebApiParameter_serviceid_actionid_name unique (serviceid, actionid, name) ); create index Index_BPAWebApiParameter_serviceid on BPAWebApiParameter(serviceid); create index Index_BPAWebApiParameter_actionid on BPAWebApiParameter(actionid); create table BPAWebApiCustomOutputParameter ( id int not null identity constraint PK_BPAWebApiCustomOutputParameter primary key, actionid int not null constraint FK_BPAWebApiCustomOutputParameter_BPAWebApiAction foreign key references BPAWebApiAction (actionid), name nvarchar(255) not null, path nvarchar(max) not null, datatype nvarchar(16) not null ); create index Index_BPAWebApiCustomOutputParameter_actionid on BPAWebApiCustomOutputParameter(actionid); create table BPAPackageWebApi( packageid int not null constraint FK_BPAPackageWebApi_BPAPackage foreign key references BPAPackage(id) on delete cascade, webapiid uniqueidentifier not null constraint FK_BPAPackageWebApi_BPAWebApiService foreign key references BPAWebApiService(serviceid) on delete cascade, constraint PK_BPAPackageWebApi primary key (packageid, webapiid) ); create table BPAProcessWebApiDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessWebApiDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refApiName nvarchar(128) not null, constraint PK_BPAProcessWebApiDependency primary key (id) ); insert into BPAValCheck ([checkid], [catid], [typeid], [description], [enabled]) values (144, 0, 0, ''Web API Business Object Action input collection mismatch{0}: {1}'', 1) ')exec('')exec('insert into BPAValCheck ([checkid], [catid], [typeid], [description], [enabled]) values (145, 0, 1, ''The collection stage used{0} in the Web API Business Object Action inputs has no defined fields: {1}'', 1) ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''256'', GETUTCDATE(), ''db_upgradeR256.sql'', ''Add Web API tables, modify the existing web service permission and add new Web API permission'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='257') begin exec('alter table BPACredentials add credentialType nvarchar(50) null ')exec('')exec('update BPACredentials set credentialType = ''General'' ')exec('')exec('alter table BPACredentials alter column credentialType nvarchar(50) not null ')exec('')exec('insert into BPADBVersion values ( ''257'', GETUTCDATE(), ''db_upgradeR257.sql UTC'', ''Add column to credentials for type'', 0 ) ') end
if not exists (select 1 from BPADBVersion where dbversion='258') begin exec('alter table BPACredentials alter column login nvarchar(max) not null ')exec('')exec('insert into BPADBVersion values ( ''258'', GETUTCDATE(), ''db_upgradeR258.sql UTC'', ''Remove length restriction from the BPACredentials login column'', 0 ) ') end
if not exists (select 1 from BPADBVersion where dbversion='259') begin exec('create table BPASysWebConnectionSettings( maxidletime int, connectionlimit int) ')exec('')exec('insert into BPASysWebConnectionSettings values (5,2) ')exec('')exec('create table BPASysWebUrlSettings( baseuri varchar(max) not null, connectionlimit int not null, connectiontimeout int null, maxidletime int not null) ')exec('')exec('insert into BPAPerm ([name]) values (''System - Web Connection Settings'') ')exec('')exec('declare @permId as int select @permId = id from bpaperm where [name] = ''System - Web Connection Settings'' insert into BPAPermGroupMember (permgroupid, permid) values (7, @permId) insert into BPAUserRolePerm (userroleid, permid) values (1, @permId) ')exec('')exec('insert into BPADBVersion values ( ''259'', getutcdate(), ''db_upgradeR259.sql'', ''Add new table for web connection settings. Add new associated permission and add to system group.'', 0 ) ') end
if not exists (select 1 from BPADBVersion where dbversion='260') begin exec('create table BPASkill ( id uniqueidentifier not null constraint PK_BPASkill primary key clustered, [provider] nvarchar(max) not null, isenabled bit not null default 1 ); create table BPASkillVersion ( id uniqueidentifier not null constraint PK_BPASkillVersion primary key clustered, skillid uniqueidentifier not null constraint FK_BPASkillVersion_BPASkill foreign key references BPASkill(id) on delete cascade, [name] nvarchar(max) not null, versionnumber nvarchar(255) not null, [description] nvarchar(max) not null, category nvarchar(max) not null, icon nvarchar(max) not null, bpversioncreated nvarchar(255), bpversiontested nvarchar(255), importedat datetime not null, importedby uniqueidentifier not null constraint FK_BPASkillVersion_BPAUser foreign key references BPAUser(userid) ); create table BPAWebSkillVersion ( versionid uniqueidentifier not null constraint PK_BPAWebSkillVersion primary key clustered constraint FK_BPAWebSkillVersion_BPASkillVersion foreign key references BPASkillVersion(id) on delete cascade, webserviceid uniqueidentifier not null constraint FK_BPAWebSkillVersion_BPAWebApiService foreign key references BPAWebApiService(serviceid) ); insert into BPADBVersion values ( ''260'', getutcdate(), ''db_upgradeR260.sql'', ''Add basic table structure for Skills'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='261') begin exec('alter table BPAWebApiCustomOutputParameter add outputparametertype int not null default 1 ')exec('')exec('alter table BPAWebApiAction add outputparametercode varchar(max) null ')exec('')exec('insert into BPADBVersion values ( ''261'', getutcdate(), ''db_upgradeR261.sql'', ''Add new type column to BPAWebApiCustomOutputParameter table and outputparametercode column to BPAWebAPIAction'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='262') begin exec('insert into BPAPerm ([name]) values (''View Skill''),(''Manage Skill''),(''Import Skill''); insert into BPAPermGroup ([name]) values(''Skills''); declare @skillGroupId as int select @skillGroupId = id from BPAPermGroup where [name] = ''Skills'' insert into BPAPermGroupMember (permgroupid, permid) select @skillGroupId, id from BPAPerm where [name] in (''View Skill'', ''Manage Skill'', ''Import Skill''); insert into BPAUserRolePerm (userroleid, permid) select r.id, m.permid from BPAUserRole r cross join BPAPermGroupMember m where r.name = ''System Administrators'' and m.permgroupid = @skillGroupId ')exec('')exec('insert into BPADBVersion values ( ''262'', getutcdate(), ''db_upgradeR262.sql'', ''Add new View, Manage and Import Skill permissions.'', 0 ) ') end
if not exists (select 1 from BPADBVersion where dbversion='263') begin exec('IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPATaskSession'') AND NAME =''IX_BPATaskSession_taskid'') DROP INDEX [IX_BPATaskSession_taskid] ON [BPATaskSession]; ')exec('')exec('CREATE INDEX [IX_BPATaskSession_taskid] ON [BPATaskSession] (taskid); IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPAScheduleLogEntry'') AND NAME =''IX_BPAScheduleLogEntry_logsess'') DROP INDEX [IX_BPAScheduleLogEntry_logsess] ON [BPAScheduleLogEntry]; ')exec('')exec('CREATE INDEX [IX_BPAScheduleLogEntry_logsess] ON [BPAScheduleLogEntry] (logsessionnumber); IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPAScheduleTrigger'') AND NAME =''IX_BPAScheduleTrigger_schedule'') DROP INDEX [IX_BPAScheduleTrigger_schedule] ON [BPAScheduleTrigger]; ')exec('')exec('CREATE INDEX [IX_BPAScheduleTrigger_schedule] ON [BPAScheduleTrigger] (ScheduleId); insert into BPADBVersion values ( ''263'', getutcdate(), ''db_upgradeR263.sql'', ''Add missing scheduler indexes'', 0 ) ') end
if not exists (select 1 from BPADBVersion where dbversion='264') begin exec('INSERT INTO BPAValCheck(checkid, catid, typeid, [description], [enabled]) VALUES(146, 1, 0, ''The Skill ''''{0}'''' is not installed or is unavailable.'', 1); INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''264'', getutcdate(), ''db_upgradeR264.sql'', ''Add validation message for clsSkillStage.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='265') begin exec('create table BPAProcessSkillDependency ( id int identity not null, processID uniqueidentifier not null constraint FK_BPAProcessSkillDependency_BPAProcess foreign key references BPAProcess(processid) on delete cascade, refSkillId uniqueidentifier not null, constraint PK_BPAProcessSkillDependency primary key (id) ); insert into BPADBVersion values ( ''265'', getutcdate(), ''db_upgradeR265.sql'', ''Add dependency table for skills'', 0 ) ') end
if not exists (select 1 from BPADBVersion where dbversion='266') begin exec('if DATABASE_PRINCIPAL_ID(''bpa_ExecuteSP_System'') is not null begin grant execute on object::usp_GetCacheETag to bpa_ExecuteSP_System; grant execute on object::usp_SetCacheETag to bpa_ExecuteSP_System; end INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''266'', getutcdate(), ''db_upgradeR266.sql'', ''Give usp_cacheETag procedures execute permissions.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='267') begin exec('ALTER TABLE BPASysWebConnectionSettings ADD connectiontimeout int null INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''267'', getutcdate(), ''db_upgradeR267.sql'', ''Add connectiontimeout column to BPASysWebConnectionSettings'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='268') begin exec('declare @rolename nvarchar(max); set @rolename = ''Release Managers''; declare @newname nvarchar(max); set @newname = @rolename declare @suffix nvarchar(max); set @suffix = '' (previousx)''; declare @id int; set @id = 0; while exists (select 1 from BPAUserRole where [name] = @newname) begin set @newname = @rolename + REPLACE(@suffix, ''x'', case when @id = 0 then '''' else cast(@id as nvarchar(10)) end); set @id += 1; end if @newname <> @rolename update BPAUserRole set [name] = @newname where [name] = @rolename; insert into BPAUserRole ([name], ssogroup) values(@rolename, ''''); insert into BPAUserRolePerm(userroleid, permid) select @@IDENTITY, permid from BPAPermGroupMember where permgroupid in (select id from BPAPermGroup where [name] in (''Release Manager'', ''Skills'')); INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''268'', getutcdate(), ''db_upgradeR268.sql'', ''Add Release Managers role to BPAUserRole and link to permissions.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='269') begin exec('IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPAWorkQueueItem'') AND NAME =''Index_BPAWorkQueueItem_queuepriorityloaded'') DROP INDEX [Index_BPAWorkQueueItem_queuepriorityloaded] ON [BPAWorkQueueItem]; ')exec('')exec('CREATE NONCLUSTERED INDEX [Index_BPAWorkQueueItem_queuepriorityloaded] ON [BPAWorkQueueItem] ( [queueident] ASC, [priority] ASC, [loaded] ASC ) INCLUDE (sessionId, finished, keyvalue, deferred, id) WITH (FILLFACTOR = 90) INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''269'', getutcdate(), ''db_upgradeR269.sql'', ''Change index on BPAWorkQueueItems'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='270') begin exec('declare @rolename nvarchar(max); set @rolename = ''Web Service Consumers''; declare @newname nvarchar(max); set @newname = @rolename; declare @suffix nvarchar(max); set @suffix = '' (previousx)''; declare @id int; set @id = 0; while exists (select 1 from BPAUserRole where [name] = @newname) begin set @newname = @rolename + REPLACE(@suffix, ''x'', case when @id = 0 then '''' else cast(@id as nvarchar(10)) end); set @id += 1; end if @newname <> @rolename update BPAUserRole set [name] = @newname where [name] = @rolename; update BPAUserRole set [name] = @rolename where [name] = ''Web Service Consumer''; INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''270'', getutcdate(), ''db_upgradeR270.sql'', ''Pluralise Web Service Consumer role'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='271') begin exec('IF COL_LENGTH(''BPATask'', ''delayafterend'') IS NULL BEGIN ALTER TABLE BPATask ADD delayafterend INT NOT NULL DEFAULT 0; END INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''271'', getutcdate(), ''db_upgradeR271.sql'', ''Add delayafterend column to BPATask table.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='272') begin exec('IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPAWorkQueueItem'') AND NAME =''Index_BPAWorkQueueItem_queueident_exception'') DROP INDEX [Index_BPAWorkQueueItem_queueident_exception] ON [BPAWorkQueueItem]; ')exec('')exec('CREATE NONCLUSTERED INDEX [Index_BPAWorkQueueItem_queueident_exception] ON [BPAWorkQueueItem] ([queueident], [exception]) INCLUDE ([id],[attempt],[loaded]) IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPAWorkQueueItem'') AND NAME =''Index_BPAWorkQueueItem_queueident_completed'') DROP INDEX [Index_BPAWorkQueueItem_queueident_completed] ON [BPAWorkQueueItem]; ')exec('')exec('CREATE NONCLUSTERED INDEX [Index_BPAWorkQueueItem_queueident_completed] ON [BPAWorkQueueItem] ([queueident] ASC, [completed] ASC) INCLUDE ([id],[attempt],[loaded],[exception],[exceptionreason]) INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''272'', getutcdate(), ''db_upgradeR272.sql'', ''BPAWorkQueueItem indexes used to optimise retrieval of actioned items'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='273') begin exec('INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''273'', getutcdate(), ''db_upgradeR273.sql'', ''Placeholder for patch script'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='274') begin exec('IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPAWorkQueueItem'') AND NAME =''Index_BPAWorkQueueItem_queueident_finished'') DROP INDEX [Index_BPAWorkQueueItem_queueident_finished] ON [BPAWorkQueueItem] ')exec('')exec('CREATE NONCLUSTERED INDEX [Index_BPAWorkQueueItem_queueident_finished] ON [BPAWorkQueueItem] ([queueident],[finished]) INCLUDE ([completed],[exception],[deferred],[attemptworktime]) WITH (FILLFACTOR = 90) ')exec('')exec('INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''274'', getutcdate(), ''db_upgradeR274.sql'', ''BPAWorkQueueItem indexes used to optimise retrieval of queue stats'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='275') begin exec('IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPASession'') AND NAME =''Index_statusID'') DROP INDEX [Index_statusID] ON [BPASession]; ')exec('')exec('IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPASession'') AND NAME =''Index_BPASession_statusid'') DROP INDEX [Index_BPASession_statusid] ON [BPASession]; ')exec('')exec('CREATE INDEX [Index_BPASession_statusid] ON [BPASession] ([statusid]) INCLUDE ([processid], [starterresourceid], [starteruserid], [runningresourceid], [queueid]) WITH (FILLFACTOR=90) IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPASession'') AND NAME =''Index_BPASession_Queueid_Status_Not_6'') DROP INDEX [Index_BPASession_Queueid_Status_Not_6] ON [BPASession]; ')exec('')exec('CREATE NONCLUSTERED INDEX [Index_BPASession_Queueid_Status_Not_6] ON [BPASession] (Queueid) WHERE StatusId <> 6 WITH (FILLFACTOR=90) IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPACaseLock'') AND NAME =''Index_BPACaseLock_locktime'') DROP INDEX [Index_BPACaseLock_locktime] ON [BPACaseLock]; ')exec('')exec('CREATE NONCLUSTERED INDEX [Index_BPACaseLock_locktime] ON [BPACaseLock] ([locktime]) INCLUDE ([id]) WITH (FILLFACTOR = 90) INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''275'', getutcdate(), ''db_upgradeR275.sql'', ''Changed Indexing of BPASession and BPACaseLock'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='276') begin exec('INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''276'', getutcdate(), ''db_upgradeR276.sql'', ''Add usp_GetSchedules stored procedure.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='277') begin exec('ALTER TABLE [BPAPermGroup] ADD [showInUi] BIT NOT NULL DEFAULT (1) ALTER TABLE [BPAPerm] ADD [showInUi] BIT NOT NULL DEFAULT (1) ALTER TABLE [BPAUserRole] ADD [showInUi] BIT NOT NULL DEFAULT (1) ')exec('')exec('DECLARE @showInUi BIT = 0 DECLARE @idTable TABLE([id] INT) INSERT INTO [BPAPermGroup] ([name], [showInUi]) OUTPUT inserted.id INTO @idTable VALUES (''Document Processing'', @showInUi) DECLARE @permGroupId INT = (SELECT TOP 1 id FROM @idTable) DELETE FROM @idTable INSERT INTO [BPAPerm] ([name], [treeid], [showInUi]) OUTPUT inserted.id INTO @idTable VALUES (''Document Processing - Create Batch'', NULL, @showInUi) DECLARE @permId INT = (SELECT TOP 1 id FROM @idTable) DELETE FROM @idTable INSERT INTO [BPAPermGroupMember] ([permgroupid], [permid]) VALUES (@permGroupId, @permId) DECLARE @systemAdminRoleId INT = ( SELECT TOP 1 [id] FROM [BPAUserRole] WHERE [name] = ''System Administrators'') INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@permId, @systemAdminRoleId) INSERT INTO [BPAUserRole] ([name], [showInUi]) OUTPUT inserted.id INTO @idTable VALUES (''Document Processing User'', @showInUi) DECLARE @roleId INT = (SELECT TOP 1 id FROM @idTable) DELETE FROM @idTable INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@permId, @roleId) INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''277'', getutcdate(), ''db_upgradeR277.sql'', ''Add document processing permissions.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='278') begin exec('CREATE TABLE [BPADocumentProcessingQueueOverride]( [batchid] [uniqueidentifier] NOT NULL, [queueid] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_BPADocumentProcessingQueueOverride] PRIMARY KEY CLUSTERED ( [batchid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] DECLARE @idTable TABLE([id] INT) INSERT INTO [BPAPerm] ([name], [treeid], [showInUi]) OUTPUT inserted.id INTO @idTable VALUES (''Document Processing - Redirect Output'', NULL, 0) DECLARE @permId INT = (SELECT TOP 1 id FROM @idTable) DELETE FROM @idTable DECLARE @permGroupId INT = ( SELECT TOP 1 [id] FROM [BPAPermGroup] WHERE [name] = ''Document Processing'') DECLARE @systemAdminRoleId INT = ( SELECT TOP 1 [id] FROM [BPAUserRole] WHERE [name] = ''System Administrators'') DECLARE @documentProcessingRoleId INT = ( SELECT TOP 1 [id] FROM [BPAUserRole] WHERE [name] = ''Document Processing User'') INSERT INTO [BPAPermGroupMember] ([permgroupid], [permid]) VALUES (@permGroupId, @permId) INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@permId, @systemAdminRoleId) INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@permId, @documentProcessingRoleId) INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''278'', getutcdate(), ''db_upgradeR278.sql'', ''Create document processing queue override table.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='279') begin exec('DECLARE @idTable TABLE([id] INT) INSERT INTO [BPAPerm] ([name], [treeid], [showInUi]) OUTPUT inserted.id INTO @idTable VALUES (''Document Processing - Configuration'', NULL, 0) DECLARE @permId INT = (SELECT TOP 1 id FROM @idTable) DELETE FROM @idTable DECLARE @permGroupId INT = ( SELECT TOP 1 [id] FROM [BPAPermGroup] WHERE [name] = ''Document Processing'') DECLARE @systemAdminRoleId INT = ( SELECT TOP 1 [id] FROM [BPAUserRole] WHERE [name] = ''System Administrators'') DECLARE @documentProcessingRoleId INT = ( SELECT TOP 1 [id] FROM [BPAUserRole] WHERE [name] = ''Document Processing User'') INSERT INTO [BPAPermGroupMember] ([permgroupid], [permid]) VALUES (@permGroupId, @permId) INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@permId, @systemAdminRoleId) INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@permId, @documentProcessingRoleId) INSERT INTO BPADBVersion VALUES ( ''279'', GETUTCDATE(), ''db_upgradeR279.sql'', ''Add permission for document processing queues system menu'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='280') begin exec('CREATE PROCEDURE #usp_dropShowUiDefault @tableName NVARCHAR(100) AS BEGIN DECLARE @command NVARCHAR(MAX) = ( SELECT TOP 1 ''ALTER TABLE ['' + t.name + ''] DROP CONSTRAINT ['' + d.name + '']'' FROM sys.default_constraints d JOIN sys.tables t ON t.object_id = d.parent_object_id WHERE t.name = @tableName AND d.name LIKE ''%showI%'' ORDER BY t.name) EXEC(@command) END ')exec('')exec('IF COL_LENGTH(''BPAPerm'',''requiredFeature'') IS NULL BEGIN ALTER TABLE [BPAPerm] ADD [requiredFeature] NVARCHAR(100) NOT NULL CONSTRAINT BPAPerm_default_requiredFeature DEFAULT '''' END IF COL_LENGTH(''BPAPermGroup'',''requiredFeature'') IS NULL BEGIN ALTER TABLE [BPAPermGroup] ADD [requiredFeature] NVARCHAR(100) NOT NULL CONSTRAINT BPAPermGroup_default_requiredFeature DEFAULT '''' END IF COL_LENGTH(''BPAUserRole'',''requiredFeature'') IS NULL BEGIN ALTER TABLE [BPAUserRole] ADD [requiredFeature] NVARCHAR(100) NOT NULL CONSTRAINT BPAUserRole_default_requiredFeature DEFAULT '''' END ')exec('')exec('UPDATE [BPAPerm] SET [requiredFeature] = ''DocumentProcessing'' WHERE [showInUi] = 0 UPDATE [BPAPermGroup] SET [requiredFeature] = ''DocumentProcessing'' WHERE [showInUi] = 0 UPDATE [BPAUserRole] SET [requiredFeature] = ''DocumentProcessing'' WHERE [showInUi] = 0 EXEC #usp_dropShowUiDefault ''BPAPerm'' EXEC #usp_dropShowUiDefault ''BPAPermGroup'' EXEC #usp_dropShowUiDefault ''BPAUserRole'' ALTER TABLE [BPAPerm] DROP COLUMN [showInUi] ALTER TABLE [BPAPermGroup] DROP COLUMN [showInUi] ALTER TABLE [BPAUserRole] DROP COLUMN [showInUi] INSERT INTO BPADBVersion VALUES ( ''280'', GETUTCDATE(), ''db_upgradeR280.sql'', ''Change showInUi field to instead reference a specific feature'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='281') begin exec('CREATE TABLE [BPADocumentTypeQueues]( [documentType] [uniqueidentifier] NOT NULL, [queue] [uniqueidentifier] NULL ) ON [PRIMARY] CREATE TABLE [BPADocumentTypeDefaultQueue]( [queue] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_BPADocumentTypeDefaultQueue] PRIMARY KEY CLUSTERED ([queue] ASC) ) ON [PRIMARY] ')exec('')exec('IF NOT EXISTS(SELECT [name] FROM [BPAWorkQueue] WHERE [name] like ''Document Processing Queue'') BEGIN DECLARE @idTable TABLE (id UNIQUEIDENTIFIER NOT NULL) INSERT INTO [BPAWorkQueue] ([id], [name], [keyfield], [running], [maxattempts], [targetsessions]) OUTPUT inserted.id INTO @idTable VALUES (NEWID(), ''Document Processing Queue'', ''Document ID'', 1, 1, 0) INSERT INTO [BPADocumentTypeDefaultQueue] SELECT TOP 1 id FROM @idTable END INSERT INTO BPADBVersion VALUES ( ''281'', GETUTCDATE(), ''db_upgradeR281.sql'', ''Add default document processing queue'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='282') begin exec('IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = ''P'' AND object_id = OBJECT_ID(''BPDS_HoursSpentWorkingQueuesByMonth'')) BEGIN EXEC(N''create procedure BPDS_HoursSpentWorkingQueuesByMonth as begin set nocount on; end'') END ')exec('')exec('ALTER procedure BPDS_HoursSpentWorkingQueuesByMonth @NumberOfMonths int = 6, @QueueName nvarchar(max) = null as IF @NumberOfMonths < 1 RAISERROR(''@NumberOfMonths must be 1 or greater'', 11, 1); SET @QueueName = ISNULL(LTRIM(RTRIM(@QueueName)), ''''); IF @QueueName = '''' BEGIN SELECT Results.[Month], CAST(ROUND(SUM(Results.Seconds/3600), 0) AS FLOAT) AS HoursWorked FROM ( SELECT CAST(TheYear as char(4)) + ''-'' + RIGHT(''00'' + CAST(TheMonth AS VARCHAR(2)), 2) As [Month], 0.00 as Seconds FROM ufn_GetReportMonths(@NumberOfMonths) UNION ALL SELECT CAST(reportyear as char(4)) + ''-'' + RIGHT(''00'' + CAST(reportmonth AS VARCHAR(2)), 2) AS [Month], (completed + exceptioned) * avgworktime AS Seconds FROM BPMIProductivityMonthly pm INNER JOIN ufn_GetReportMonths(@NumberOfMonths) ON TheYear = reportyear AND TheMonth = reportmonth) Results GROUP BY Results.[Month] ORDER BY Results.[Month] ASC END ELSE BEGIN SELECT Results.[Month], CAST(ROUND(SUM(Results.Seconds/3600), 0) AS FLOAT) AS HoursWorked FROM (SELECT CAST(TheYear as char(4)) + ''-'' + RIGHT(''00'' + CAST(TheMonth AS VARCHAR(2)), 2) As [Month], 0.00 as Seconds FROM ufn_GetReportMonths(@NumberOfMonths) UNION ALL SELECT CAST(reportyear as char(4)) + ''-'' + RIGHT(''00'' + CAST(reportmonth AS VARCHAR(2)), 2) AS [Month], (completed + exceptioned) * avgworktime AS Seconds FROM BPMIProductivityMonthly pm INNER JOIN ufn_GetReportMonths(@NumberOfMonths) ON TheYear = reportyear AND TheMonth = reportmonth INNER JOIN BPAWorkQueue wq ON pm.queueident = wq.ident WHERE wq.[name] = @QueueName) Results GROUP BY Results.[Month] ORDER BY Results.[Month] ASC END return; ')exec('')exec('INSERT INTO BPATile(id, [name], tiletype, [description], autorefresh, xmlproperties) VALUES(NEWID(), ''Hours Spent Working Queues'', 1, ''Hours spent by Digital Workers on one or more Work Queues on a monthly basis.'', 0, ''<Chart type="3" plotByRow="false"><Procedure name="BPDS_HoursSpentWorkingQueuesByMonth" /></Chart>''); GRANT EXECUTE ON OBJECT::BPDS_HoursSpentWorkingQueuesByMonth TO bpa_ExecuteSP_DataSource_bpSystem; INSERT INTO BPATileDataSources(spname, tiletype, helppage) VALUES(''BPDS_HoursSpentWorkingQueuesByMonth'', 1, ''HoursSpentWorkingQueuesByMonth.htm''); INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''282'', getutcdate(), ''db_upgradeR282.sql'', ''Add dashboard tile to show hours spent working on work queues.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='283') begin exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''283'', getutcdate(), ''db_upgradeR283.sql'', ''Make changes to usp_getnextcase to fix duplicate work queue items being retrieved. '', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='284') begin exec('if (select InstallInProgress from BPVScriptEnvironment) = 1 update BPAMIControl set mienabled=1, autorefresh=1, refreshat=DATEADD(HOUR, 1, CAST(FLOOR(CAST(GETDATE() as float)) as datetime)); insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''284'', getutcdate(), ''db_upgradeR284.sql'', ''Enable MI reporting by default for new installations.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='285') begin exec('ALTER TABLE BPAWorkQueue DROP CONSTRAINT Index_name ')exec('')exec('UPDATE BPAWorkQueue SET [name]='''' WHERE [name] IS NULL ALTER TABLE BPAWorkQueue ALTER COLUMN [name] NVARCHAR(255) NOT NULL ALTER TABLE BPAWorkQueue ADD CONSTRAINT Index_name UNIQUE NONCLUSTERED([name]) ')exec('')exec('DECLARE @userid UNIQUEIDENTIFIER SET @userid = (SELECT TOP 1 userid FROM BPAUser) UPDATE BPAProcess SET [name]='''' WHERE [name] IS NULL ALTER TABLE BPAProcess ALTER COLUMN [name] NVARCHAR(128) NOT NULL UPDATE BPAProcess SET ProcessType=''P'' WHERE ProcessType IS NULL ALTER TABLE BPAProcess ALTER COLUMN ProcessType NVARCHAR(1) NOT NULL UPDATE BPAProcess SET createdate=CAST(''1753-1-1'' AS DATETIME) WHERE createdate IS NULL ALTER TABLE BPAProcess ALTER COLUMN createdate DATETIME NOT NULL UPDATE BPAProcess SET createdby=@userid WHERE createdby IS NULL ALTER TABLE BPAProcess ALTER COLUMN createdby UNIQUEIDENTIFIER NOT NULL UPDATE BPAProcess SET lastmodifieddate=GETUTCDATE() WHERE lastmodifieddate IS NULL ALTER TABLE BPAProcess ALTER COLUMN lastmodifieddate DATETIME NOT NULL UPDATE BPAProcess SET lastmodifiedby=@userid WHERE lastmodifiedby IS NULL ALTER TABLE BPAProcess ALTER COLUMN lastmodifiedby UNIQUEIDENTIFIER NOT NULL IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPASession'') AND NAME =''Index_BPASession_statusid'') DROP INDEX [Index_BPASession_statusid] ON [BPASession]; ')exec('')exec('IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPASession'') AND NAME =''Index_BPASession_Queueid_Status_Not_6'') DROP INDEX [Index_BPASession_Queueid_Status_Not_6] ON [BPASession]; ')exec('')exec('UPDATE BPASession SET statusid=0 WHERE statusid IS NULL ALTER TABLE BPASession ALTER COLUMN statusid INT NOT NULL CREATE INDEX Index_BPASession_statusid ON BPASession (statusid) INCLUDE (processid,starterresourceid,starteruserid,runningresourceid,queueid) WITH (FILLFACTOR = 90) CREATE NONCLUSTERED INDEX Index_BPASession_Queueid_Status_Not_6 ON BPASession (Queueid) WHERE StatusId <> 6 WITH (FILLFACTOR = 90) ')exec('')exec('ALTER TABLE BPAResource DROP CONSTRAINT UNQ_BPAResource_name ')exec('')exec('UPDATE BPAResource SET [name]='''' WHERE [name] IS NULL ALTER TABLE BPAResource ALTER COLUMN [name] NVARCHAR(128) NOT NULL ')exec('')exec('ALTER TABLE BPAResource ADD CONSTRAINT UNQ_BPAResource_name unique (name) IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPAResource'') AND NAME =''IX_UNQ_BPAResource_Name'') DROP INDEX [IX_UNQ_BPAResource_Name] ON [BPAResource]; ')exec('')exec('CREATE UNIQUE INDEX IX_UNQ_BPAResource_Name ON BPAResource([name]) INCLUDE (resourceid, fqdn) WITH (FILLFACTOR = 90) IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPAResource'') AND NAME =''INDEX_BPAResource_SSL'') DROP INDEX [INDEX_BPAResource_SSL] ON [BPAResource]; ')exec('')exec('CREATE NONCLUSTERED INDEX INDEX_BPAResource_SSL ON BPAResource([name]) INCLUDE ([SSL]) WITH (FILLFACTOR = 90) ALTER TABLE BPAResource ADD statusid INT NOT NULL DEFAULT 0 ')exec('')exec('UPDATE BPAResource SET statusid=0 where [status]=''Unknown'' UPDATE BPAResource SET statusid=1 where [status]=''Ready'' UPDATE BPAResource SET statusid=2 where [status]=''Offline'' UPDATE BPAResource SET statusid=3 where [status]=''Pending'' ')exec('')exec('ALTER VIEW BPVGroupedResources AS SELECT g.treeid AS treeid, (CASE WHEN r.[pool] IS NOT NULL THEN r.[pool] ELSE g.id END) AS groupid, g.name AS groupname, r.resourceid AS id, r.name AS name, r.attributeid AS attributes, CASE WHEN r.[pool] IS NOT NULL THEN 1 ELSE 0 END AS ispoolmember, 1 AS statusid FROM BPAResource r LEFT JOIN ( BPAGroupResource gr INNER JOIN BPAGroup g ON gr.groupid = g.id ) ON gr.memberid = r.resourceid WHERE attributeId & 8 = 0; ')exec('')exec('ALTER VIEW BPVPools AS SELECT g.treeid AS treeid, g.id AS groupid, g.name AS groupname, r.resourceid AS id, r.name AS name, r.attributeid AS attributes, r.statusid AS statusid FROM BPAResource r LEFT JOIN ( BPAGroupResource gr INNER JOIN BPAGroup g ON gr.groupid = g.id ) ON gr.memberid = r.resourceid WHERE attributeId & 8 = 8; ')exec('')exec('ALTER TABLE BPAResource DROP COLUMN DisplayStatus ')exec('')exec('ALTER TABLE BPAResource ADD DisplayStatus AS ( CASE WHEN (AttributeID & 13) <> 0 THEN null WHEN statusid = 2 THEN ''Offline'' WHEN DATEDIFF(second, lastupdated, GETUTCDATE()) >= 60 THEN ''Missing'' WHEN (AttributeID & 16) <> 0 THEN ''Logged Out'' WHEN (AttributeID & 32) <> 0 THEN ''Private'' WHEN actionsrunning = 0 THEN ''Idle'' ELSE ''Working'' END); ')exec('')exec('ALTER TABLE BPAResource DROP COLUMN [status] UPDATE BPAMIControl SET mienabled = 0 WHERE mienabled IS NULL ALTER TABLE BPAMIControl ALTER COLUMN mienabled BIT NOT NULL UPDATE BPAMIControl SET autorefresh = 0 WHERE autorefresh IS NULL ALTER TABLE BPAMIControl ALTER COLUMN autorefresh BIT NOT NULL UPDATE BPAMIControl SET refreshinprogress = 0 WHERE refreshinprogress IS NULL ALTER TABLE BPAMIControl ALTER COLUMN refreshinprogress BIT NOT NULL UPDATE BPAMIControl SET dailyfor = 30 WHERE dailyfor IS NULL ALTER TABLE BPAMIControl ALTER COLUMN dailyfor INT NOT NULL UPDATE BPAMIControl SET monthlyfor = 6 WHERE monthlyfor IS NULL ALTER TABLE BPAMIControl ALTER COLUMN monthlyfor INT NOT NULL IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''BPATag'') AND NAME =''UNQ_BPATag_tag'') DROP INDEX [UNQ_BPATag_tag] ON [BPATag]; ')exec('')exec('UPDATE BPATag SET tag = '''' WHERE tag IS NULL ALTER TABLE BPATag ALTER COLUMN tag NVARCHAR(255) NOT NULL ')exec('')exec('CREATE UNIQUE INDEX UNQ_BPATag_tag ON BPATag(tag) WITH (FILLFACTOR = 90) ')exec('')exec('INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''285'', GETUTCDATE(), ''db_upgradeR285.sql'', ''Performance enhancements'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='286') begin exec('DECLARE @idTable TABLE([id] INT) DECLARE @docProcessingPermGroupId INT = ( SELECT [id] FROM [BPAPermGroup] WHERE [name] = ''Document Processing'' ) INSERT INTO [BPAPerm] ([name], [treeid], [requiredFeature]) OUTPUT inserted.id INTO @idTable VALUES (''Document Processing - View Document'', NULL, ''DocumentProcessing'') DECLARE @viewDocumentPermId INT = (SELECT TOP 1 id FROM @idTable) DELETE FROM @idTable INSERT INTO [BPAPerm] ([name], [treeid], [requiredFeature]) OUTPUT inserted.id INTO @idTable VALUES (''Document Processing - View Document Data'', NULL, ''DocumentProcessing'') DECLARE @viewDocumentDataPermId INT = (SELECT TOP 1 id FROM @idTable) DELETE FROM @idTable INSERT INTO [BPAPermGroupMember] ([permgroupid], [permid]) VALUES (@docProcessingPermGroupId, @viewDocumentPermId) INSERT INTO [BPAPermGroupMember] ([permgroupid], [permid]) VALUES (@docProcessingPermGroupId, @viewDocumentDataPermId) DECLARE @systemAdminRoleId INT = ( SELECT TOP 1 [id] FROM [BPAUserRole] WHERE [name] = ''System Administrators'') INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@viewDocumentPermId, @systemAdminRoleId) INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@viewDocumentDataPermId, @systemAdminRoleId) DECLARE @docProcessingUserRoleId INT = ( SELECT Id FROM [BPAUserRole] WHERE [name] = ''Document Processing User'' ) INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@viewDocumentPermId, @docProcessingUserRoleId) INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@viewDocumentDataPermId, @docProcessingUserRoleId) INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''286'', getutcdate(), ''db_upgradeR286.sql'', ''Add additional document processing permissions.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='287') begin exec('IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''BPAResourceAttribute'') BEGIN TRUNCATE TABLE [BPAResourceAttribute] INSERT INTO [BPAResourceAttribute] (AttributeID, AttributeName) VALUES(0,''None'') INSERT INTO [BPAResourceAttribute] (AttributeID, AttributeName) VALUES(1,''Retired'') INSERT INTO [BPAResourceAttribute] (AttributeID, AttributeName) VALUES(2,''Local'') INSERT INTO [BPAResourceAttribute] (AttributeID, AttributeName) VALUES(4,''Debug'') INSERT INTO [BPAResourceAttribute] (AttributeID, AttributeName) VALUES(8,''Pool'') INSERT INTO [BPAResourceAttribute] (AttributeID, AttributeName) VALUES(16,''LoginAgent'') INSERT INTO [BPAResourceAttribute] (AttributeID, AttributeName) VALUES(32,''Private'') END IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''BPAProcessAttribute'') BEGIN TRUNCATE TABLE [BPAProcessAttribute] INSERT INTO [BPAProcessAttribute] (AttributeID, AttributeName) VALUES(0,''None'') INSERT INTO [BPAProcessAttribute] (AttributeID, AttributeName) VALUES(1,''Retired'') INSERT INTO [BPAProcessAttribute] (AttributeID, AttributeName) VALUES(2,''Published'') INSERT INTO [BPAProcessAttribute] (AttributeID, AttributeName) VALUES(4,''PublishedWS'') END INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''287'', getutcdate(), ''db_upgradeR287.sql'', ''Synchronise the BPAResourceAttribute Table with the ResourceAttribute Enum, and the BPAProcessAttribute Table with the ProcessAttribute Enum.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='288') begin exec('alter table BPAWorkQueueItem add locktime datetime NULL, lockid uniqueidentifier null; ')exec('')exec('alter procedure usp_getnextcase @queuename NVARCHAR(255), @keyfilter NVARCHAR(255) = NULL, @sess UNIQUEIDENTIFIER = NULL, @ontag1 NVARCHAR(255) = NULL, @ontag2 NVARCHAR(255) = NULL, @ontag3 NVARCHAR(255) = NULL, @ontag4 NVARCHAR(255) = NULL, @ontag5 NVARCHAR(255) = NULL, @ontag6 NVARCHAR(255) = NULL, @ontag7 NVARCHAR(255) = NULL, @ontag8 NVARCHAR(255) = NULL, @ontag9 NVARCHAR(255) = NULL, @offtag1 NVARCHAR(255) = NULL, @offtag2 NVARCHAR(255) = NULL, @offtag3 NVARCHAR(255) = NULL, @offtag4 NVARCHAR(255) = NULL, @offtag5 NVARCHAR(255) = NULL, @offtag6 NVARCHAR(255) = NULL, @offtag7 NVARCHAR(255) = NULL, @offtag8 NVARCHAR(255) = NULL, @offtag9 NVARCHAR(255) = NULL AS DECLARE @sql NVARCHAR(MAX); DECLARE @params NVARCHAR(MAX); DECLARE @selected TABLE (encryptid INT, id UNIQUEIDENTIFIER, ident BIGINT, keyvalue NVARCHAR(255), data NVARCHAR(MAX), STATUS NVARCHAR(255), attempt INT, lockid UNIQUEIDENTIFIER, locktime DATETIME, sessionid UNIQUEIDENTIFIER ); DECLARE @lockid UNIQUEIDENTIFIER; SET @lockid = NEWID(); IF OBJECT_ID(''tempdb..#ontags'') IS NOT NULL DROP TABLE #ontags; IF OBJECT_ID(''tempdb..#offtags'') IS NOT NULL DROP TABLE #offtags; CREATE TABLE #ontags(id INT); CREATE TABLE #offtags(id INT); IF @ontag1 IS NOT NULL AND @ontag1 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag1; IF @ontag2 IS NOT NULL AND @ontag2 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag2; IF @ontag3 IS NOT NULL AND @ontag3 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag3; IF @ontag4 IS NOT NULL AND @ontag4 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag4; IF @ontag5 IS NOT NULL AND @ontag5 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag5; IF @ontag6 IS NOT NULL AND @ontag6 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag6; IF @ontag7 IS NOT NULL AND @ontag7 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag7; IF @ontag8 IS NOT NULL AND @ontag8 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag8; IF @ontag9 IS NOT NULL AND @ontag9 NOT LIKE ''%[_%]%'' INSERT INTO #ontags EXEC usp_gettagids @tag = @ontag9; IF EXISTS ( SELECT 1 FROM #ontags WHERE id IS NULL ) RETURN; IF @offtag1 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag1; IF @offtag2 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag2; IF @offtag3 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag3; IF @offtag4 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag4; IF @offtag5 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag5; IF @offtag6 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag6; IF @offtag7 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag7; IF @offtag8 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag8; IF @offtag9 IS NOT NULL INSERT INTO #offtags EXEC usp_gettagids @tag = @offtag9; DELETE FROM #offtags WHERE id IS NULL; SET @sql = '' set transaction isolation level read uncommitted; with cte AS (select top(1) i.* from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident where i.lockid is null and q.name = @queuename and q.running = 1 and i.finished is null and (i.deferred is null or i.deferred < getutcdate()) ''; IF @keyfilter IS NOT NULL BEGIN SET @sql = @sql + '' and i.keyvalue = @keyfilter''; END; IF EXISTS ( SELECT 1 FROM #ontags ) BEGIN SET @sql = @sql + '' and ( select count(*) from BPAWorkQueueItemTag it join #ontags ot on it.tagid = ot.id where it.queueitemident = i.ident ) = (select count(*) from #ontags) ''; END; DECLARE @onwildcardsql NVARCHAR(MAX); SET @onwildcardsql = '' and exists ( select 1 from BPAWorkQueueItemTag it join BPATag t on it.tagid = t.id where it.queueitemident = i.ident and t.tag like @ontag''; IF @ontag1 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''1)''; IF @ontag2 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''2)''; IF @ontag3 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''3)''; IF @ontag4 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''4)''; IF @ontag5 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''5)''; IF @ontag6 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''6)''; IF @ontag7 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''7)''; IF @ontag8 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''8)''; IF @ontag9 LIKE ''%[_%]%'' SET @sql = @sql + @onwildcardsql + ''9)''; IF EXISTS ( SELECT 1 FROM #offtags ) BEGIN SET @sql = @sql + '' and not exists ( select 1 from BPAWorkQueueItemTag it join #offtags ot on it.tagid = ot.id where it.queueitemident = i.ident ) ''; END; SET @sql = @sql + '' order by i.priority, i.loaded, i.ident) update a set locktime = getutcdate(), lockid = @lockid OUTPUT inserted.encryptid, inserted.id, inserted.ident, inserted.keyvalue, inserted.data, inserted.status, inserted.attempt, inserted.lockid, inserted.locktime, inserted.sessionid FROM cte a; ''; SET @params = '' @sess uniqueidentifier, @queuename nvarchar(255), @keyfilter nvarchar(255), @lockid uniqueidentifier, @ontag1 nvarchar(255), @ontag2 nvarchar(255), @ontag3 nvarchar(255), @ontag4 nvarchar(255), @ontag5 nvarchar(255), @ontag6 nvarchar(255), @ontag7 nvarchar(255), @ontag8 nvarchar(255), @ontag9 nvarchar(255) ''; DECLARE @attempt INT, @maxattempts INT; SET @maxattempts = 100; SET @attempt = 1; WHILE @attempt <= @maxattempts BEGIN BEGIN TRY BEGIN TRAN; INSERT INTO @selected EXEC sp_executesql @sql, @params, @sess = @sess, @queuename = @queuename, @keyfilter = @keyfilter, @lockid = @lockid, @ontag1 = @ontag1, @ontag2 = @ontag2, @ontag3 = @ontag3, @ontag4 = @ontag4, @ontag5 = @ontag5, @ontag6 = @ontag6, @ontag7 = @ontag7, @ontag8 = @ontag8, @ontag9 = @ontag9; IF(EXISTS ( SELECT 1 FROM @selected )) BEGIN COMMIT; END; ELSE BEGIN ROLLBACK; RETURN; END; IF(EXISTS ( SELECT 1 FROM BPAWorkQueueItem WHERE lockID = @lockId )) BREAK; END TRY BEGIN CATCH IF ERROR_NUMBER() = 2627 OR ERROR_NUMBER() = 1205 BEGIN IF(@@trancount > 0) BEGIN ROLLBACK; END; SET @attempt = @attempt + 1; IF @attempt <= @maxattempts CONTINUE; END; EXEC usp_rethrow; RETURN; END CATCH; END; IF(EXISTS ( SELECT 1 FROM @selected )) BEGIN INSERT INTO BPACaseLock (id, locktime, sessionid, lockid ) SELECT i.ident, i.locktime, sessionid = CASE WHEN @sess IS NULL THEN i.sessionid ELSE @sess END, @lockid FROM @selected i WHERE i.lockid = @lockid; END; SELECT i.encryptid, i.id, i.ident, i.keyvalue, i.data, i.STATUS, i.attempt FROM @selected i; ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''288'', getutcdate(), ''db_upgradeR288.sql'', ''Improve robustness of work queue item locking.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='289') begin exec('declare @OldPermName as nvarchar(50) ,@NewPermName as nvarchar(50) set @OldPermName = N''System - Web Connection Settings''; set @NewPermName = N''Business Objects - Web Connection Settings''; update BPAPerm set name = @NewPermName where name = @OldPermName; ')exec('')exec('insert into BPADBVersion values ( ''289'', getutcdate(), ''db_upgradeR289.sql'', ''Updated permission name for web connection settings from System to Business Objects.'', 0 ) ') end
if not exists (select 1 from BPADBVersion where dbversion='290') begin exec('DECLARE @idTable TABLE([id] INT) DECLARE @docProcessingPermGroupId INT = ( SELECT [id] FROM [BPAPermGroup] WHERE [name] = ''Document Processing'' ) INSERT INTO [BPAPerm] ([name], [treeid], [requiredFeature]) OUTPUT inserted.id INTO @idTable VALUES (''ViewBatchType'', NULL, ''DocumentProcessing'') DECLARE @viewBatchTypePermId INT = (SELECT TOP 1 id FROM @idTable) DELETE FROM @idTable INSERT INTO [BPAPermGroupMember] ([permgroupid], [permid]) VALUES (@docProcessingPermGroupId, @viewBatchTypePermId) DECLARE @systemAdminRoleId INT = ( SELECT TOP 1 [id] FROM [BPAUserRole] WHERE [name] = ''System Administrators'') INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@viewBatchTypePermId, @systemAdminRoleId) DECLARE @docProcessingUserRoleId INT = ( SELECT Id FROM [BPAUserRole] WHERE [name] = ''Document Processing User'' ) INSERT INTO [BPAUserRolePerm] ([permid], [userroleid]) VALUES (@viewBatchTypePermId, @docProcessingUserRoleId) INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''290'', getutcdate(), ''db_upgradeR290.sql'', ''Add additional document processing permissions.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='291') begin exec('ALTER procedure [usp_getnextcase] @queuename nvarchar(255), @keyfilter nvarchar(255) = null, @sess uniqueidentifier = null, @ontag1 nvarchar(255) = null, @ontag2 nvarchar(255) = null, @ontag3 nvarchar(255) = null, @ontag4 nvarchar(255) = null, @ontag5 nvarchar(255) = null, @ontag6 nvarchar(255) = null, @ontag7 nvarchar(255) = null, @ontag8 nvarchar(255) = null, @ontag9 nvarchar(255) = null, @offtag1 nvarchar(255) = null, @offtag2 nvarchar(255) = null, @offtag3 nvarchar(255) = null, @offtag4 nvarchar(255) = null, @offtag5 nvarchar(255) = null, @offtag6 nvarchar(255) = null, @offtag7 nvarchar(255) = null, @offtag8 nvarchar(255) = null, @offtag9 nvarchar(255) = null as declare @sql nvarchar(max); declare @params nvarchar(max); declare @lockid uniqueidentifier; set @lockid = newid(); if object_id(''tempdb..#ontags'') is not null drop table #ontags; if object_id(''tempdb..#offtags'')is not null drop table #offtags; create table #ontags (id int); create table #offtags (id int); if @ontag1 is not null and @ontag1 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag1; if @ontag2 is not null and @ontag2 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag2; if @ontag3 is not null and @ontag3 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag3; if @ontag4 is not null and @ontag4 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag4; if @ontag5 is not null and @ontag5 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag5; if @ontag6 is not null and @ontag6 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag6; if @ontag7 is not null and @ontag7 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag7; if @ontag8 is not null and @ontag8 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag8; if @ontag9 is not null and @ontag9 not like ''%[_%]%'' insert into #ontags exec usp_gettagids @tag=@ontag9; if exists (select 1 from #ontags where id is null) return; if @offtag1 is not null insert into #offtags exec usp_gettagids @tag=@offtag1; if @offtag2 is not null insert into #offtags exec usp_gettagids @tag=@offtag2; if @offtag3 is not null insert into #offtags exec usp_gettagids @tag=@offtag3; if @offtag4 is not null insert into #offtags exec usp_gettagids @tag=@offtag4; if @offtag5 is not null insert into #offtags exec usp_gettagids @tag=@offtag5; if @offtag6 is not null insert into #offtags exec usp_gettagids @tag=@offtag6; if @offtag7 is not null insert into #offtags exec usp_gettagids @tag=@offtag7; if @offtag8 is not null insert into #offtags exec usp_gettagids @tag=@offtag8; if @offtag9 is not null insert into #offtags exec usp_gettagids @tag=@offtag9; delete from #offtags where id is null; set @sql = '' set transaction isolation level read uncommitted; insert into BPACaseLock (id,locktime,sessionid,lockid) select top 1 i.ident ,getutcdate() ,case when @sess is null then i.sessionid else @sess end ,@lockid from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident left join BPACaseLock l on l.id = i.ident where q.name = @queuename and q.running = 1 and i.finished is null and (i.deferred is null or i.deferred < getutcdate()) and l.id is null ''; if @keyfilter is not null begin SET @sql = @sql + '' and i.keyvalue = @keyfilter''; end if exists (select 1 from #ontags) begin set @sql = @sql + '' and ( select count(*) from BPAWorkQueueItemTag it join #ontags ot on it.tagid = ot.id where it.queueitemident = i.ident ) = (select count(*) from #ontags) ''; end declare @onwildcardsql nvarchar(max) set @onwildcardsql = '' and exists ( select 1 from BPAWorkQueueItemTag it join BPATag t on it.tagid = t.id where it.queueitemident = i.ident and t.tag like @ontag''; if @ontag1 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''1)''; if @ontag2 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''2)''; if @ontag3 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''3)''; if @ontag4 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''4)''; if @ontag5 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''5)''; if @ontag6 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''6)''; if @ontag7 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''7)''; if @ontag8 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''8)''; if @ontag9 like ''%[_%]%'' set @sql = @sql + @onwildcardsql + ''9)''; if exists (select 1 from #offtags) begin set @sql = @sql + '' and not exists ( select 1 from BPAWorkQueueItemTag it join #offtags ot on it.tagid = ot.id where it.queueitemident = i.ident ) ''; end set @sql = @sql + '' order by i.priority, i.loaded, i.ident; ''; set @params = '' @sess uniqueidentifier, @queuename nvarchar(255), @keyfilter nvarchar(255), @lockid uniqueidentifier, @ontag1 nvarchar(255), @ontag2 nvarchar(255), @ontag3 nvarchar(255), @ontag4 nvarchar(255), @ontag5 nvarchar(255), @ontag6 nvarchar(255), @ontag7 nvarchar(255), @ontag8 nvarchar(255), @ontag9 nvarchar(255) ''; declare @attempt int, @maxattempts int; set @maxattempts = 100; set @attempt = 1; while @attempt <= @maxattempts begin begin try Begin TRAN DECLARE @appLock int DECLARE @lockName VARCHAR(255) = ''GetNextCaseLock-'' + @queuename EXEC @appLock = sp_getapplock @Resource=@lockName, @LockMode=''Exclusive'', @LockOwner=''Transaction'', @LockTimeout = 100 if @appLock < 0 BEGIN ROLLBACK set @attempt = @attempt + 1; if @attempt <= @maxattempts continue; ELSE THROW 51000, ''Failed to get app lock for work queue item'',1 END ELSE BEGIN exec sp_executesql @sql,@params,@sess=@sess,@queuename=@queuename,@keyfilter=@keyfilter,@lockid=@lockid,@ontag1=@ontag1,@ontag2=@ontag2,@ontag3=@ontag3,@ontag4=@ontag4,@ontag5=@ontag5,@ontag6=@ontag6,@ontag7=@ontag7,@ontag8=@ontag8,@ontag9=@ontag9; COMMIT break; END end try begin catch IF(@@trancount > 0) BEGIN ROLLBACK; END; ELSE BEGIN EXEC sp_releaseapplock @Resource = ''BPAWorkQueueItem''; END if error_number() = 2627 begin set @attempt = @attempt + 1; if @attempt <= @maxattempts continue; end; exec usp_rethrow; return; end catch end; select i.encryptid, i.id, i.ident, i.keyvalue, i.data, i.status, i.attempt from BPAWorkQueueItem i join BPAWorkQueue q on i.queueident = q.ident join BPACaseLock l on i.ident = l.id where l.lockid = @lockid; ')exec('')exec('INSERT INTO BPADBVersion VALUES ( ''291'', GETUTCDATE(), ''db_upgradeR291.sql'', ''Eliminate duplicates returned by usp_GetNextCase'',0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='292') begin exec('INSERT INTO BPADBVersion VALUES ( ''292'', GETUTCDATE(), ''db_upgradeR292.sql UTC'', ''Add columns for Work Queue Analysis setting'', 0) ') end
if not exists (select 1 from BPADBVersion where dbversion='293') begin exec('declare @docPermissions table([name] nvarchar(100)) insert into @docPermissions(name) values(''ViewBatch'') insert into @docPermissions(name) values(''DeleteBatch'') insert into @docPermissions(name) values(''VerifyBatch'') insert into @docPermissions(name) values(''ViewBatchOutput'') insert into @docPermissions(name) values(''ModifyDocument'') insert into @docPermissions(name) values(''ViewPage'') insert into @docPermissions(name) values(''ModifyFormData'') insert into @docPermissions(name) values(''CreateFieldTemplate'') insert into @docPermissions(name) values(''ModifyFieldTemplate'') insert into @docPermissions(name) values(''ViewFieldTemplate'') insert into @docPermissions(name) values(''DeleteFieldTemplate'') insert into @docPermissions(name) values(''CreateUserAccount'') insert into @docPermissions(name) values(''ViewUserAccount'') insert into @docPermissions(name) values(''CreateBatchType'') insert into @docPermissions(name) values(''ModifyBatchType'') insert into @docPermissions(name) values(''DeleteBatchType'') insert into @docPermissions(name) values(''CreateDocumentType'') insert into @docPermissions(name) values(''ModifyDocumentType'') insert into @docPermissions(name) values(''ViewDocumentType'') insert into @docPermissions(name) values(''DeleteDocumentType'') delete @docPermissions where name in (select name from BPAPerm) declare @idTable table(id int) insert into BPAPerm (name, treeid, requiredFeature) output inserted.id into @idTable select name, null, ''DocumentProcessing'' from @docPermissions declare @permGroupId int = (select top 1 p.id from BPAPermGroup p where p.name = ''Document Processing'') insert into BPAPermGroupMember (permgroupid, permid) select @permGroupId, id from @idTable declare @roleId int = (select top 1 id from BPAUserRole where name = ''Document Processing User'') declare @userRolePerm table(userroleid int, permid int) insert into @userRolePerm select @roleId, i.id from @idTable i delete @userRolePerm from @userRolePerm temp join BPAUserRolePerm urp on temp.permid = urp.permid and temp.userroleid = urp.userroleid insert into BPAUserRolePerm select rp.userRoleId, rp.permId from @userRolePerm rp IF NOT EXISTS(SELECT 1 FROM sys.columns WHERE Name = N''activationdate'' AND Object_ID = Object_ID(N''BPALicense'')) BEGIN ALTER TABLE BPALicense ADD activationdate datetime NULL END ')exec('')exec('IF NOT EXISTS(SELECT 1 FROM sys.columns WHERE Name = N''activatedby'' AND Object_ID = Object_ID(N''BPALicense'')) BEGIN ALTER TABLE BPALicense ADD activatedby uniqueidentifier NULL END ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''293'', getutcdate(), ''db_upgradeR293.sql'', ''Add additional document processing permissions.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='294') begin exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''294'', getutcdate(), ''db_upgradeR294.sql'', ''Placeholder script for patch 6.4.2 changes.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='295') begin exec('IF COL_LENGTH(''BPASysConfig'', ''DatabaseInstallerOptions'') IS NULL ALTER TABLE BPASysConfig ADD DatabaseInstallerOptions INT ')exec('')exec('EXEC sp_rename ''BPASessionLog_Unicode'',''BPASessionLog_Unicode_pre65'' EXEC sp_rename ''PK_BPASessionLog_Unicode'',''PK_BPASessionLog_Unicode_pre65'' EXEC sp_rename ''FK_BPASessionLog_Unicode_BPASession'',''FK_BPASessionLog_Unicode_BPASession_pre65'' ')exec('')exec('CREATE TABLE BPASessionLog_Unicode ( logid BIGINT NOT NULL IDENTITY(1,1), sessionnumber INT NOT NULL, stageid uniqueidentifier NULL, stagename NVARCHAR(128) NULL, stagetype INT NULL, processname NVARCHAR(128) NULL, pagename NVARCHAR(128) NULL, objectname NVARCHAR(128) NULL, actionname NVARCHAR(128) NULL, result NVARCHAR(max) NULL, resulttype INT NULL, startdatetime DATETIME NULL, enddatetime DATETIME NULL, attributexml NVARCHAR(max) NULL, automateworkingset BIGINT NULL, targetappname NVARCHAR(32) NULL, targetappworkingset BIGINT NULL, starttimezoneoffset INT NULL, endtimezoneoffset INT NULL, attributesize as ISNULL(DATALENGTH(attributexml),0) PERSISTED, CONSTRAINT PK_BPASessionLog_Unicode PRIMARY KEY (logid) ) ')exec('')exec('IF EXISTS (SELECT 1 FROM BPASysConfig WHERE DatabaseInstallerOptions & 1 = 1) BEGIN DECLARE @BatchSize INT = 50000; WHILE EXISTS(SELECT 1 FROM BPASessionLog_Unicode_pre65) BEGIN INSERT INTO BPASessionLog_Unicode SELECT TOP (@BatchSize) sessionnumber, stageid, stagename, stagetype, processname, pagename, objectname, actionname, result, resulttype, startdatetime, enddatetime, attributexml, automateworkingset, targetappname, targetappworkingset, starttimezoneoffset, endtimezoneoffset FROM BPASessionLog_Unicode_pre65 ORDER BY sessionnumber, seqnum; WITH CTE AS ( SELECT TOP (@BatchSize) * FROM BPASessionLog_Unicode_pre65 ORDER BY sessionnumber, seqnum ) DELETE FROM CTE END END ')exec('')exec('ALTER TABLE BPASessionLog_Unicode ADD CONSTRAINT FK_BPASessionLog_Unicode_BPASession FOREIGN KEY (sessionnumber) REFERENCES BPASession(sessionnumber) CREATE INDEX Index_BPASessionLog_Unicode_sessionnumber ON BPASessionLog_Unicode (sessionnumber) WITH (FILLFACTOR = 90) ')exec('')exec('IF EXISTS (SELECT 1 FROM BPASysConfig WHERE DatabaseInstallerOptions & 1 = 1) BEGIN ALTER TABLE BPASessionLog_Unicode_pre65 DROP CONSTRAINT FK_BPASessionLog_Unicode_BPASession_pre65; ALTER TABLE BPASessionLog_Unicode_pre65 DROP CONSTRAINT PK_BPASessionLog_Unicode_pre65; DROP TABLE BPASessionLog_Unicode_pre65; END ')exec('')exec('EXEC sp_rename ''BPASessionLog_NonUnicode'',''BPASessionLog_NonUnicode_pre65'' EXEC sp_rename ''PK_BPASessionLog_NonUnicode'',''PK_BPASessionLog_NonUnicode_pre65'' EXEC sp_rename ''FK_BPASessionLog_NonUnicode_BPASession'',''FK_BPASessionLog_NonUnicode_BPASession_pre65'' ')exec('')exec('CREATE TABLE BPASessionLog_NonUnicode ( logid BIGINT NOT NULL IDENTITY(1,1), sessionnumber INT NOT NULL, stageid uniqueidentifier NULL, stagename VARCHAR(128) NULL, stagetype INT NULL, processname VARCHAR(128) NULL, pagename VARCHAR(128) NULL, objectname VARCHAR(128) NULL, actionname VARCHAR(128) NULL, result VARCHAR(max) NULL, resulttype INT NULL, startdatetime DATETIME NULL, enddatetime DATETIME NULL, attributexml VARCHAR(max) NULL, automateworkingset BIGINT NULL, targetappname VARCHAR(32) NULL, targetappworkingset BIGINT NULL, starttimezoneoffset INT NULL, endtimezoneoffset INT NULL, attributesize as ISNULL(DATALENGTH(attributexml),0) PERSISTED, CONSTRAINT PK_BPASessionLog_NonUnicode PRIMARY KEY (logid) ) ')exec('')exec('IF EXISTS (SELECT 1 FROM BPASysConfig WHERE DatabaseInstallerOptions & 1 = 1) BEGIN DECLARE @BatchSize INT = 50000; WHILE EXISTS(SELECT 1 FROM BPASessionLog_NonUnicode_pre65) BEGIN INSERT INTO BPASessionLog_NonUnicode SELECT TOP (@BatchSize) sessionnumber, stageid, stagename, stagetype, processname, pagename, objectname, actionname, result, resulttype, startdatetime, enddatetime, attributexml, automateworkingset, targetappname, targetappworkingset, starttimezoneoffset, endtimezoneoffset FROM BPASessionLog_NonUnicode_pre65 ORDER BY sessionnumber, seqnum; WITH CTE AS ( SELECT TOP (@BatchSize) * FROM BPASessionLog_NonUnicode_pre65 ORDER BY sessionnumber, seqnum ) DELETE FROM CTE END END ')exec('')exec('ALTER TABLE BPASessionLog_NonUnicode ADD CONSTRAINT FK_BPASessionLog_NonUnicode_BPASession FOREIGN KEY (sessionnumber) REFERENCES BPASession(sessionnumber) CREATE INDEX Index_BPASessionLog_NonUnicode_sessionnumber ON BPASessionLog_NonUnicode (sessionnumber) WITH (FILLFACTOR = 90) ')exec('')exec('IF EXISTS (SELECT 1 FROM BPASysConfig WHERE DatabaseInstallerOptions & 1 = 1) BEGIN ALTER TABLE BPASessionLog_NonUnicode_pre65 DROP CONSTRAINT FK_BPASessionLog_NonUnicode_BPASession_pre65; ALTER TABLE BPASessionLog_NonUnicode_pre65 DROP CONSTRAINT PK_BPASessionLog_NonUnicode_pre65; DROP TABLE BPASessionLog_NonUnicode_pre65; END ')exec('')exec('INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''295'', GETUTCDATE(), ''db_upgradeR295.sql'', ''Improve performance of BPASessionLogs'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='296') begin exec('CREATE TABLE BPASnapshotConfiguration ( id INT IDENTITY, interval INT NOT NULL DEFAULT 2, name NVARCHAR(255), timezone VARCHAR(255), startsecsaftermidnight INT NOT NULL, endsecsaftermidnight INT NOT NULL, sunday BIT, monday BIT, tuesday BIT, wednesday BIT, thursday BIT, friday BIT, saturday BIT, isenabled BIT, CONSTRAINT PK_BPASnapshotConfiguration PRIMARY KEY (id) ) ALTER TABLE BPAWorkQueue ADD lastsnapshotid BIGINT, snapshotconfigurationid INT, CONSTRAINT FK_BPAWorkQueue_BPASnapshotConfiguration FOREIGN KEY (snapshotconfigurationid) REFERENCES BPASnapshotConfiguration (id) ')exec('')exec('CREATE TABLE BPMIConfiguredSnapshot ( snapshotid BIGINT NOT NULL IDENTITY, queueident INT NOT NULL, timeofdaysecs INT NOT NULL, dayofweek INT, interval INT NOT NULL DEFAULT 2, eventtype INT NOT NULL, CONSTRAINT PK_BPMIConfiguredSnapshot PRIMARY KEY (snapshotid), CONSTRAINT FK_BPMIConfiguredSnapshot_BPAWorkQueue FOREIGN KEY (queueident) REFERENCES BPAWorkQueue (ident) ON DELETE CASCADE ); create nonclustered index Index_BPMIConfiguredSnapshot_queueident on BPMIConfiguredSnapshot (queueident) with (fillfactor = 90); CREATE TABLE BPMIQueueSnapshot ( id BIGINT NOT NULL IDENTITY, queueident INT NOT NULL, snapshotid BIGINT NOT NULL, snapshotdate DATETIMEOFFSET NOT NULL, capturedatetimeutc DATETIME NOT NULL DEFAULT GETUTCDATE(), totalitems INT NOT NULL, itemspending INT NOT NULL, itemscompleted INT NOT NULL, itemsreferred INT NOT NULL, newitemsdelta INT NOT NULL, completeditemsdelta INT NOT NULL, referreditemsdelta INT NOT NULL, totalworktimecompleted BIGINT NOT NULL, totalworktimereferred BIGINT NOT NULL, totalidletime BIGINT NOT NULL, totalnewsincemidnight INT NOT NULL, totalnewlast24hours INT NOT NULL, averagecompletedworktime INT NOT NULL, averagereferredworktime INT NOT NULL, averageidletime INT NOT NULL, CONSTRAINT PK_BPMIQueueSnapshot PRIMARY KEY (id), CONSTRAINT FK_BPMIQueueSnapshot_BPAWorkQueue FOREIGN KEY (queueident) REFERENCES BPAWorkQueue (ident) ON DELETE CASCADE ); create nonclustered index Index_BPMIQueueSnapshot_snapshotid_queueident on BPMIQueueSnapshot (snapshotid, queueident) with (fillfactor = 90); CREATE TABLE BPMIQueueTrend ( id INT NOT NULL IDENTITY, snapshottimeofdaysecs INT, queueident INT NOT NULL, trendid INT NOT NULL, capturedatetimeutc DATETIME NOT NULL DEFAULT GETUTCDATE(), averagetotalitems INT NOT NULL, averageitemspending INT NOT NULL, averageitemscompleted INT NOT NULL, averageitemsreferred INT NOT NULL, averagenewitemsdelta INT NOT NULL, averagecompleteditemsdelta INT NOT NULL, averagereferreditemsdelta INT NOT NULL, averagetotalworktimecompleted BIGINT NOT NULL, averagetotalworktimereferred BIGINT NOT NULL, averagetotalidletime BIGINT NOT NULL, averagetotalnewsincemidnight INT NOT NULL, averagetotalnewlast24hours INT NOT NULL, averageaveragecompletedworktime INT NOT NULL, averageaveragereferredworktime INT NOT NULL, averageaverageidletime INT NOT NULL, CONSTRAINT PK_BPMIQueueTrend PRIMARY KEY (id), CONSTRAINT FK_BPMIQueueTrend_BPAWorkQueue FOREIGN KEY (queueident) REFERENCES BPAWorkQueue (ident) ON DELETE CASCADE ); create nonclustered index Index_BPMIQueueTrend_queueident on BPMIQueueTrend (queueident) with (fillfactor = 90); create table BPMIQueueInterimSnapshot( queueident int not null, snapshotdate datetimeoffset not null, totalitems int not null, itemspending int not null, itemscompleted int not null, itemsreferred int not null, newitemsdelta int not null, completeditemsdelta int not null, referreditemsdelta int not null, totalworktimecompleted bigint not null, totalworktimereferred bigint not null, totalidletime bigint not null, constraint PK_BPMIQueueInterimSnapshot primary key clustered (queueident), constraint FK_BPMIQueueInterimSnapshot_BPAWorkQueue foreign key (queueident) references BPAWorkQueue (ident) on delete cascade); INSERT INTO BPADBVersion VALUES ( ''296'', GETUTCDATE(), ''db_upgradeR296.sql UTC'', ''Update and create tables for Work Queue Analysis'', 0) ') end
if not exists (select 1 from BPADBVersion where dbversion='297') begin exec('DECLARE @ImportReleaseId INT; DECLARE @NewDatabaseInstallation INT = (SELECT InstallInProgress FROM BPVScriptEnvironment); DECLARE @ReleaseManagerGroupId INT = (SELECT TOP 1 id FROM BPAPermGroup WHERE [name] = ''Release Manager''); INSERT INTO BPAPerm([name]) VALUES(''Import Release''); SET @ImportReleaseId = SCOPE_IDENTITY(); INSERT INTO BPAPermGroupMember(permgroupid, permid) VALUES(@ReleaseManagerGroupId, @ImportReleaseId); IF (@NewDatabaseInstallation = 1) BEGIN DECLARE @SystemAdminUserRoleId INT = (SELECT TOP 1 id FROM BPAUserRole WHERE [name] = ''System Administrators''); DECLARE @ReleaseManagersUserRoleId INT = (SELECT TOP 1 id FROM BPAUserRole WHERE [name] = ''Release Managers''); INSERT INTO BPAUserRolePerm(userroleid, permid) SELECT BPAUserRole.id, @ImportReleaseId FROM BPAUserRole WHERE BPAUserRole.id = @SystemAdminUserRoleId OR BPAUserRole.id = @ReleaseManagersUserRoleId; END ELSE BEGIN INSERT INTO BPAUserRolePerm(userroleid, permid) SELECT BPAUserRolePerm.userroleid, @ImportReleaseId FROM BPAUserRolePerm INNER JOIN BPAPerm ON BPAUserRolePerm.permid = BPAPerm.id WHERE BPAPerm.[name] = ''View Release Manager''; END INSERT INTO BPADBVersion VALUES ( ''297'', GETUTCDATE(), ''db_upgradeR297.sql'', ''Add ImportRelease permission and automatically assign it based on current roles/permissions.'', 0) ') end
if not exists (select 1 from BPADBVersion where dbversion='298') begin exec('alter table BPMIProductivityShadow add statewhendeleted int null; create nonclustered index Index_BPMIProductivityShadow_queueident_eventdatetime_eventid on BPMIProductivityShadow (queueident, eventdatetime, eventid) include (worktime, elapsedtime, statewhendeleted) with (fillfactor = 90); INSERT INTO BPADBVersion VALUES ( ''298'', GETUTCDATE(), ''db_upgradeR298.sql'', ''Add item state at point of deletion to queue item MI shadow table.'', 0) ') end
if not exists (select 1 from BPADBVersion where dbversion='299') begin exec('CREATE TABLE BPADataPipelineInput ( id bigint primary key identity(1,1) not null, eventtype integer not null, [eventdata] nvarchar(max) not null, publisher nvarchar(200) not null, inserttime datetime default(GETUTCDATE()) ) CREATE TABLE BPADataPipelineProcessConfig( id int primary key identity(1,1), [name] nvarchar(100) not null, encryptid int, [configfile] nvarchar(max), CONSTRAINT FK_BPADataPipelineProcessConfig_BPAKeyStore_ID FOREIGN KEY (encryptid) REFERENCES BPAKeyStore(id) ); CREATE TABLE BPADataPipelineProcess ( id int primary key identity(1,1), [name] nvarchar(max) not null, [status] int not null, [message] nvarchar(max), [lastupdated] datetime default(GETUTCDATE()), [config] int, [tcpEndpoint] nvarchar(max) not null CONSTRAINT FK_BPADataPipelineProcess_BPADataPipelineProcessConfig_ID FOREIGN KEY ([config]) REFERENCES BPADataPipelineProcessConfig(id) ); insert into BPAPerm ([name]) values (''Data Gateways - Configuration''), (''Data Gateways - Advanced Configuration''), (''Data Gateways - Control Room''); declare @sysManGroupId as int declare @controlRoomGroupId as int select @sysManGroupId = id from BPAPermGroup where [name] = ''System Manager'' select @controlRoomGroupId = id from BPAPermGroup where [name] = ''Control Room'' insert into BPAPermGroupMember (permgroupid, permid) select @sysManGroupId, id from BPAPerm where [name] in (''Data Gateways - Configuration'', ''Data Gateways - Advanced Configuration''); insert into BPAPermGroupMember (permgroupid, permid) select @controlRoomGroupId, id from BPAPerm where [name] = ''Data Gateways - Control Room''; insert into BPAUserRolePerm (userroleid, permid) select r.id, p.id from BPAUserRole r cross join BPAPerm p where r.name = ''System Administrators'' and p.name in (''Data Gateways - Configuration'', ''Data Gateways - Advanced Configuration'', ''Data Gateways - Control Room''); ')exec('')exec('INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''299'', getutcdate(), ''db_upgradeR299.sql'', ''Add data pipeline tables.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='300') begin exec('CREATE TABLE BPADataPipelineSettings ( id int not null, writesessionlogstodatabase bit not null, emitsessionlogstodatagateways bit not null, monitoringfrequency int not null, constraint PK_BPADataPipelineSettings primary key clustered (id) ) insert into BPADataPipelineSettings ([id], [writesessionlogstodatabase], [emitsessionlogstodatagateways], [monitoringfrequency]) values (1,1,0,5); INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''300'', getutcdate(), ''db_upgradeR300.sql'', ''Add data pipeline config tables.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='301') begin exec('ALTER TABLE BPADashboard ADD sendeveryseconds INT NOT NULL default 3600 ALTER TABLE BPADataPipelineSettings ADD sendpublisheddashboardstodatagateways bit default 0 INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''301'', getutcdate(), ''db_upgradeR301.sql'', ''Add data pipeline config tables.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='302') begin exec('ALTER TABLE BPADashboard ADD lastsent datetime INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''302'', getutcdate(), ''db_upgradeR302.sql'', ''Add lastSent column to BPADashboard'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='303') begin exec('declare @docProcssing as nvarchar(25) = ''DocumentProcessing'' declare @systemAdmin as nvarchar(25) = ''System Administrators'' declare @docProcessingUserRoleId as int = (select top(1) id from BPAUserRole ur where ur.requiredFeature = @docProcssing) declare @systemAdminRoleId as int = (select top(1) id from BPAUserRole ur where ur.name = @systemAdmin) declare @businessObjectId as int = (select top(1) id from BPAPerm p where p.name = ''Business Objects - Management'') delete BPAUserRolePerm where userroleid = @docProcessingUserRoleId and permid = @businessObjectId declare @idTable table(id int) insert into @idTable select p.id from BPAPerm p where p.requiredFeature = @docProcssing and p.id not in (select p.permid from BPAUserRolePerm p where p.userroleid = @docProcessingUserRoleId) insert into BPAUserRolePerm select @docProcessingUserRoleId, i.id from @idTable i insert into BPAUserRolePerm select @systemAdminRoleId, i.id from @idTable i insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''303'', getutcdate(), ''db_upgradeR303.sql'', ''Add additional document processing permissions.'', 0); select * from BPADBVersion order by scriptrundate ') end
if not exists (select 1 from BPADBVersion where dbversion='304') begin exec('IF NOT EXISTS(SELECT 1 FROM sys.columns WHERE Name = N''EnvironmentId'' AND Object_ID = Object_ID(N''BPASysConfig'')) BEGIN ALTER TABLE [BPASysConfig] ADD [EnvironmentId] uniqueidentifier NOT NULL CONSTRAINT BPASysConfig_EnvironmentId DEFAULT NEWID() END ')exec('')exec('DELETE FROM [BPALicense] WHERE LicenseKey = ''MVcwc2sCCh8MZTFONGK0jp0='' ')exec('')exec('IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[BPALicenseActivationRequest]'') AND type in (N''U'')) BEGIN CREATE TABLE [BPALicenseActivationRequest]( [RequestId] int IDENTITY(1,1) NOT NULL, [LicenseId] int NOT NULL, [UserId] uniqueidentifier NOT NULL, [RequestDateTime] datetime NOT NULL CONSTRAINT BPALicenseActivationRequest_RequestDateTime DEFAULT GETUTCDATE(), [Reference] uniqueidentifier NOT NULL CONSTRAINT BPALicenseActivationRequest_Reference DEFAULT NEWID(), [Request] varchar(max) NOT NULL, CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED ( [RequestId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY], CONSTRAINT [IX_User_Guid] UNIQUE NONCLUSTERED ( [Reference] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] END ')exec('')exec('IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[FK_BPALicenseActivationRequest_BPALicense]'') AND parent_object_id = OBJECT_ID(N''[BPALicenseActivationRequest]'')) ALTER TABLE [BPALicenseActivationRequest] WITH CHECK ADD CONSTRAINT [FK_BPALicenseActivationRequest_BPALicense] FOREIGN KEY([LicenseId]) REFERENCES [BPALicense] ([Id]) ')exec('')exec('IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[FK_BPALicenseActivationRequest_BPALicense]'') AND parent_object_id = OBJECT_ID(N''[BPALicenseActivationRequest]'')) ALTER TABLE [BPALicenseActivationRequest] CHECK CONSTRAINT [FK_BPALicenseActivationRequest_BPALicense] ')exec('')exec('IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[FK_BPALicenseActivationRequest_BPAUser]'') AND parent_object_id = OBJECT_ID(N''[BPALicenseActivationRequest]'')) ALTER TABLE [BPALicenseActivationRequest] WITH CHECK ADD CONSTRAINT [FK_BPALicenseActivationRequest_BPAUser] FOREIGN KEY([UserId]) REFERENCES [BPAUser] ([UserId]) ')exec('')exec('IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[FK_BPALicenseActivationRequest_BPAUser]'') AND parent_object_id = OBJECT_ID(N''[BPALicenseActivationRequest]'')) ALTER TABLE [BPALicenseActivationRequest] CHECK CONSTRAINT [FK_BPALicenseActivationRequest_BPAUser] ')exec('')exec('IF NOT EXISTS(SELECT 1 FROM sys.columns WHERE Name = N''licenseactivationresponse'' AND Object_ID = Object_ID(N''BPALicense'')) BEGIN ALTER TABLE BPALicense ADD licenseactivationresponse varchar(MAX) NULL END ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''304'', getutcdate(), ''db_upgradeR304.sql'', ''Added License Activation Request functionality.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='305') begin exec('DECLARE @newGroupId int DECLARE @publicHolidayId int =0 SELECT @publicHolidayId = max(id) FROM BPAPublicHoliday INSERT INTO BPAPublicHolidayGroup (name) VALUES (''USA'') SET @newGroupId = SCOPE_IDENTITY() INSERT INTO BPAPublicHoliday (id, name,dd,mm,dayofweek,nthofmonth,relativetoholiday ,relativedaydiff,eastersunday) SELECT @publicHolidayId + 1, ''New Year''''s Day'',1,1,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 2, ''Martin Luther King Jr. Day'',null,1,1,3,null,null,null UNION ALL SELECT @publicHolidayId + 3, ''Presidents'''' Day'',null,2,1,3,null,null,null UNION ALL SELECT @publicHolidayId + 4, ''Memorial Day'',null,5,1,-1,null,null,null UNION ALL SELECT @publicHolidayId + 5, ''Independence Day'',4,7,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 6, ''Labor Day'',null,9,1,1,null,null,null UNION ALL SELECT @publicHolidayId + 7, ''Columbus Day'',14,10,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 8, ''Veterans Day'',11,11,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 9, ''Thanksgiving Day'',null,11,4,4,null,null,null UNION ALL SELECT @publicHolidayId + 10, ''Christmas Day'',25,12,null,null,null,null,null INSERT INTO BPAPublicHolidayGroupMember(publicholidaygroupid, publicholidayid) SELECT @newGroupId , @publicHolidayId + 1 UNION ALL SELECT @newGroupId , @publicHolidayId + 2 UNION ALL SELECT @newGroupId , @publicHolidayId + 3 UNION ALL SELECT @newGroupId , @publicHolidayId + 4 UNION ALL SELECT @newGroupId , @publicHolidayId + 5 UNION ALL SELECT @newGroupId , @publicHolidayId + 6 UNION ALL SELECT @newGroupId , @publicHolidayId + 7 UNION ALL SELECT @newGroupId , @publicHolidayId + 8 UNION ALL SELECT @newGroupId , @publicHolidayId + 9 UNION ALL SELECT @newGroupId , @publicHolidayId + 10 INSERT INTO BPAPublicHolidayGroup (name) VALUES (''Japan'') SET @newGroupId = SCOPE_IDENTITY() INSERT INTO BPAPublicHoliday (id, name,dd,mm,dayofweek,nthofmonth,relativetoholiday ,relativedaydiff,eastersunday) SELECT @publicHolidayId + 11, ''New Year''''s Day'',1,1,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 12,''January 2 Bank Holiday'',null,null,null,null,@publicHolidayId + 11,1,null UNION ALL SELECT @publicHolidayId + 13,''January 3 Bank Holiday'',null,null,null,null,@publicHolidayId + 12,1,null UNION ALL SELECT @publicHolidayId + 14,''Coming of Age Day'',null,1,1,2,null,null,null UNION ALL SELECT @publicHolidayId + 15,''National Foundation Day'',11,2,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 16,''Shōwa'',29,4,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 17,''Constitution Memorial Day'',3,5,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 18,''Greenery Day'',null,null,null,null,@publicHolidayId + 17,1,null UNION ALL SELECT @publicHolidayId + 19,''Children''''s Day'',null,null,null,null,@publicHolidayId + 18,1,null UNION ALL SELECT @publicHolidayId + 20,''Marine Day'',null,7,1,3,null,null,null UNION ALL SELECT @publicHolidayId + 21,''Mountain Day'',11,8,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 22,''Respect for the Aged Day'',null,9,1,3,null,null,null UNION ALL SELECT @publicHolidayId + 23,''Health and Sports Day'',null,10,1,2,null,null,null UNION ALL SELECT @publicHolidayId + 24,''Culture Day'',3,11,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 25,''Labor Thanksgiving Day'',23,11,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 26,''December 31 Bank Holiday'',31,12,null,null,null,null,null INSERT INTO BPAPublicHolidayGroupMember(publicholidaygroupid, publicholidayid) SELECT @newGroupId , @publicHolidayId + 11 UNION ALL SELECT @newGroupId , @publicHolidayId + 12 UNION ALL SELECT @newGroupId , @publicHolidayId + 13 UNION ALL SELECT @newGroupId , @publicHolidayId + 14 UNION ALL SELECT @newGroupId , @publicHolidayId + 15 UNION ALL SELECT @newGroupId , @publicHolidayId + 16 UNION ALL SELECT @newGroupId , @publicHolidayId + 17 UNION ALL SELECT @newGroupId , @publicHolidayId + 18 UNION ALL SELECT @newGroupId , @publicHolidayId + 19 UNION ALL SELECT @newGroupId , @publicHolidayId + 20 UNION ALL SELECT @newGroupId , @publicHolidayId + 21 UNION ALL SELECT @newGroupId , @publicHolidayId + 22 UNION ALL SELECT @newGroupId , @publicHolidayId + 23 UNION ALL SELECT @newGroupId , @publicHolidayId + 24 UNION ALL SELECT @newGroupId , @publicHolidayId + 25 UNION ALL SELECT @newGroupId , @publicHolidayId + 26 INSERT INTO BPAPublicHolidayGroup (name) VALUES (''Hong Kong'') SET @newGroupId = SCOPE_IDENTITY() INSERT INTO BPAPublicHoliday (id, name,dd,mm,dayofweek,nthofmonth,relativetoholiday ,relativedaydiff,eastersunday) SELECT @publicHolidayId + 27, ''New Year''''s Day'',1,1,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 28, ''Hong Kong Special Administrative Region Establishment Day'',1,7,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 29, ''National Day'',1,10,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 30, ''Christmas Day'',25,12,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 31, ''Boxing Day'',null,null,null,null,@publicHolidayId + 30,1,null INSERT INTO BPAPublicHolidayGroupMember(publicholidaygroupid, publicholidayid) SELECT @newGroupId , @publicHolidayId + 27 UNION ALL SELECT @newGroupId , @publicHolidayId + 28 UNION ALL SELECT @newGroupId , @publicHolidayId + 29 UNION ALL SELECT @newGroupId , @publicHolidayId + 30 UNION ALL SELECT @newGroupId , @publicHolidayId + 31 INSERT INTO BPAPublicHolidayGroup (name) VALUES (''China'') SET @newGroupId = SCOPE_IDENTITY() INSERT INTO BPAPublicHoliday (id, name,dd,mm,dayofweek,nthofmonth,relativetoholiday ,relativedaydiff,eastersunday) SELECT @publicHolidayId + 32, ''New Year''''s Day'',1,1,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 33,''Labor Day'',1,5,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 34,''National Day'',1,10,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 35,''National Day Golden Week holiday'',2,10,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 36,''National Day Golden Week holiday'',3,10,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 37,''National Day Golden Week holiday'',4,10,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 38,''National Day Golden Week holiday'',5,10,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 39,''National Day Golden Week holiday'',6,10,null,null,null,null,null UNION ALL SELECT @publicHolidayId + 40,''National Day Golden Week holiday'',7,10,null,null,null,null,null INSERT INTO BPAPublicHolidayGroupMember(publicholidaygroupid, publicholidayid) SELECT @newGroupId , @publicHolidayId + 32 UNION ALL SELECT @newGroupId , @publicHolidayId + 33 UNION ALL SELECT @newGroupId , @publicHolidayId + 34 UNION ALL SELECT @newGroupId , @publicHolidayId + 35 UNION ALL SELECT @newGroupId , @publicHolidayId + 36 UNION ALL SELECT @newGroupId , @publicHolidayId + 37 UNION ALL SELECT @newGroupId , @publicHolidayId + 38 UNION ALL SELECT @newGroupId , @publicHolidayId + 39 UNION ALL SELECT @newGroupId , @publicHolidayId + 40 insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''305'', getutcdate(), ''db_upgradeR305.sql'', ''Added public holidays for USA, China, Hong Kong and Japan.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='306') begin exec('UPDATE [BPAPerm] SET [name] = REPLACE([name], ''Document Processing'', ''Decipher'') WHERE [requiredFeature] = ''DocumentProcessing'' UPDATE [BPAPermGroup] SET [name] = REPLACE([name], ''Document Processing'', ''Decipher'') WHERE [requiredFeature] = ''DocumentProcessing'' UPDATE [BPAUserRole] SET [name] = REPLACE([name], ''Document Processing'', ''Decipher'') WHERE [requiredFeature] = ''DocumentProcessing'' UPDATE [BPAWorkQueue] SET [name] = ''Decipher Queue'' WHERE [name] = ''Document Processing Queue'' insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''306'', getutcdate(), ''db_upgradeR306.sql'', ''Add additional document processing permissions.'', 0); select * from BPADBVersion order by scriptrundate ') end
if not exists (select 1 from BPADBVersion where dbversion='307') begin exec('IF NOT EXISTS (SELECT * FROM BPAPref WHERE [name] = ''ConnectionCheckRetrySeconds'' AND userid IS NULL) BEGIN INSERT INTO BPAPref ([name]) VALUES (''ConnectionCheckRetrySeconds'') END DECLARE @prefId INT = (SELECT TOP 1 id from BPAPref WHERE [name] = ''ConnectionCheckRetrySeconds'' AND userid IS NULL); IF NOT EXISTS (SELECT * FROM BPAIntegerPref WHERE prefid = @prefId) BEGIN INSERT INTO BPAIntegerPref (prefid, [value]) VALUES (@prefId, 5) END IF NOT EXISTS (SELECT * FROM BPADataTracker WHERE dataname = ''Preferences'') BEGIN INSERT INTO BPADataTracker (dataname, versionno) VALUES (''Preferences'', 1) END INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''307'', getutcdate(), ''db_upgradeR307.sql'', ''Add ConnectionCheckRetrySeconds to BPA Pref.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='308') begin exec('IF not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_QueueSnapshotComparison'') EXEC(N''create procedure BPDS_QueueSnapshotComparison as begin set nocount on; end''); ')exec('')exec('ALTER procedure BPDS_QueueSnapshotComparison @QueueName NVARCHAR(255) = NULL, @NumberOfSnapshottedDaysPrevious INT = 1, @ColumnIdentifier INT = 1, @TimeRangeStartTime VARCHAR(8) = NULL, @TimeRangeEndTime VARCHAR(8) = NULL AS IF @QueueName IS NULL RAISERROR(''@QueueName must be specified.'', 11, 1); IF @ColumnIdentifier < 1 or @ColumnIdentifier > 15 RAISERROR(''@ColumnIdentifier must be between 1 and 15.'', 11, 1); DECLARE @Today DATETIME; DECLARE @ColumnName NVARCHAR(255) = NULL; DECLARE @QueueIdent INT; DECLARE @PreviousSnapshotDate DATE; DECLARE @Sql NVARCHAR(MAX); DECLARE @TimeRangeStartTimeConverted TIME(7); DECLARE @TimeRangeEndTimeConverted TIME(7); DECLARE @DontUseTimeRange BIT = 1; DECLARE @TimezoneOffset INT = 0 IF @TimeRangeStartTime IS NOT NULL AND @TimeRangeEndTime IS NOT NULL BEGIN SET @TimeRangeStartTimeConverted = CAST(@TimeRangeStartTime AS TIME(7)) SET @TimeRangeEndTimeConverted = CAST(@TimeRangeEndTime AS TIME(7)) SET @DontUseTimeRange = 0; END SET @ColumnName = CASE @ColumnIdentifier WHEN 1 THEN ''totalitems'' WHEN 2 THEN ''itemspending'' WHEN 3 THEN ''itemscompleted'' WHEN 4 THEN ''itemsreferred'' WHEN 5 THEN ''newitemsdelta'' WHEN 6 THEN ''completeditemsdelta'' WHEN 7 THEN ''referreditemsdelta'' WHEN 8 THEN ''totalworktimecompleted'' WHEN 9 THEN ''totalworktimereferred'' WHEN 10 THEN ''totalidletime'' WHEN 11 THEN ''totalnewsincemidnight'' WHEN 12 THEN ''totalnewlast24hours'' WHEN 13 THEN ''averagecompletedworktime'' WHEN 14 THEN ''averagereferredworktime'' WHEN 15 THEN ''averageidletime'' ELSE ''totalitems'' END; SELECT TOP 1 @QueueIdent = ident FROM BPAWorkQueue WHERE [name] = @QueueName SELECT top 1 @TimezoneOffset = DATEPART(TZoffset, snapshotdate) FROM BPMIQueueSnapshot WHERE queueident = @QueueIdent ORDER BY snapshotdate DESC; SET @Today = CAST(DATEADD(MI, @TimezoneOffset, GETUTCDATE()) AS DATE); SELECT TOP 1 @PreviousSnapshotDate = CAST(snapshotdate AS DATE) FROM BPMIQueueSnapshot WHERE queueident = @QueueIdent AND CAST(snapshotdate AS DATE) <= DATEADD(DAY, -@NumberOfSnapshottedDaysPrevious, @Today) ORDER BY BPMIQueueSnapshot.snapshotdate DESC; IF @PreviousSnapshotDate IS NULL BEGIN RAISERROR(''Snapshot data not found.'', 11, 1); RETURN; END; SET @Sql = ''SELECT [Time], [Previous Metric], [Current Metric] FROM (SELECT CONVERT(VARCHAR(5), previous.snapshotdate, 108) as [Time], previous.'' + @ColumnName + '' as [Previous Metric], today.'' + @ColumnName + '' as [Current Metric] FROM BPMIQueueSnapshot previous LEFT JOIN BPMIQueueSnapshot today ON today.queueident = previous.queueident AND CAST(previous.snapshotdate as time) = CAST(today.snapshotdate as time) AND CAST(today.snapshotdate as date) = @Today WHERE previous.queueident = @QueueIdent AND CAST(previous.snapshotdate as date) = @PreviousSnapshotDate) Results WHERE @DontUseTimeRange = 1 OR (@TimeRangeStartTimeConverted <= Results.Time AND @TimeRangeEndTimeConverted >= Results.Time);'' EXEC sp_executesql @Sql, N''@PreviousSnapshotDate DATE, @Today DATETIME, @QueueIdent INT, @DontUseTimeRange BIT, @TimeRangeStartTimeConverted TIME(7), @TimeRangeEndTimeConverted TIME(7)'', @PreviousSnapshotDate, @Today, @QueueIdent, @DontUseTimeRange, @TimeRangeStartTimeConverted, @TimeRangeEndTimeConverted RETURN; ')exec('')exec('GRANT EXECUTE ON OBJECT::BPDS_QueueSnapshotComparison TO bpa_ExecuteSP_DataSource_bpSystem; ')exec('')exec('INSERT INTO BPATileDataSources(spname, tiletype, helppage) VALUES(''BPDS_QueueSnapshotComparison'', 1, ''QueueSnapshotComparison.htm''); INSERT INTO BPADBVersion VALUES ( ''308'', GETUTCDATE(), ''db_upgradeR308.sql UTC'', ''Create data source for comparison of snapshot data'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='309') begin exec('IF COL_LENGTH(''BPAWorkQueue'',''requiredFeature'') IS NULL BEGIN ALTER TABLE [BPAWorkQueue] ADD [requiredFeature] NVARCHAR(100) NOT NULL CONSTRAINT BPAWorkQueue_default_requiredFeature DEFAULT '''' END ')exec('')exec('UPDATE [BPAWorkQueue] SET [requiredFeature] = ''DocumentProcessing'' WHERE [name] = ''Decipher Queue'' ')exec('')exec('ALTER view [BPVGroupedQueues] as select g.treeid as treeid, g.id as groupid, g.name as groupname, q.ident as id, q.name as name, q.id as guid, q.running as running, q.encryptid as encryptid, q.processid as processid, q.resourcegroupid as resourcegroupid, q.requiredFeature as requiredFeature, case when q.processid is not null and q.resourcegroupid is not null then cast(1 as bit) else cast(0 as bit) end as isactive from BPAWorkQueue q left join ( BPAGroupQueue gq inner join BPAGroup g on gq.groupid = g.id ) on gq.memberid = q.ident; ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''309'', getutcdate(), ''db_upgradeR309.sql'', ''Add required feature column to BPAWorkQueue.'', 0); select * from BPADBVersion order by scriptrundate ') end
if not exists (select 1 from BPADBVersion where dbversion='310') begin exec('CREATE TABLE BPMISnapshotTrigger( queueident INT NOT NULL, snapshotid BIGINT NOT NULL, lastsnapshotid BIGINT NULL, eventtype INT NOT NULL, snapshotdate DATETIMEOFFSET NOT NULL, snapshotdateutc AS (CONVERT(DATETIME, DATEADD(MINUTE, -DATEPART(TZOFFSET, snapshotdate), snapshotdate))), midnightutc AS (CONVERT(DATETIME, DATEADD(MINUTE, -DATEPART(TZOFFSET, snapshotdate), TODATETIMEOFFSET(CONVERT(DATE, snapshotdate), DATEPART(TZOFFSET, snapshotdate))))), CONSTRAINT PK_BPMISnapshotTrigger PRIMARY KEY CLUSTERED (queueident, snapshotid)); IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = ''P'' AND object_id = OBJECT_ID(''usp_TriggerQueueSnapshot'')) BEGIN EXEC(N''create procedure usp_TriggerQueueSnapshot as begin set nocount on; end'') END ')exec('')exec('ALTER PROCEDURE usp_TriggerQueueSnapshot AS BEGIN declare @triggers table ( queueIdent int, snapshotId bigint, snapshotDate datetimeoffset) insert into @triggers select queueIdent, snapshotId, snapshotdate from BPMISnapshotTrigger where snapshotdateutc <= GETUTCDATE(); declare @queueIdent int, @snapshotId bigint, @snapshotDate datetimeoffset while exists (select 1 from @triggers) begin select top 1 @queueIdent = queueident, @snapshotId = snapshotId, @snapshotDate = snapshotDate from @triggers; insert into BPMIQueueSnapshot (snapshotid, queueident, snapshotdate, totalitems, itemspending, itemscompleted, itemsreferred, newitemsdelta, completeditemsdelta, referreditemsdelta, totalworktimecompleted, totalworktimereferred, totalidletime, totalnewsincemidnight, totalnewlast24hours, averagecompletedworktime, averagereferredworktime, averageidletime) values (@snapshotId, @queueIdent, @snapshotDate, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); delete from BPMISnapshotTrigger where queueident = @queueIdent and snapshotId = @snapshotId; delete from @triggers where queueIdent = @queueIdent and snapshotId = @snapshotId; end END ')exec('')exec('GRANT EXECUTE ON OBJECT::usp_TriggerQueueSnapshot TO bpa_ExecuteSP_System; INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''310'', GETUTCDATE(), ''db_upgradeR310.sql'', ''Add BPMISnapshotTrigger table and usp_TriggerQueueSnapshot stored procedure.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='311') begin exec('CREATE TABLE [BPADataPipelineOutputConfig]( [id] [INT] IDENTITY(1,1) NOT NULL, [uniquereference] [UNIQUEIDENTIFIER] NOT NULL, [name] [nvarchar](255) NOT NULL, [issessions] [bit] NOT NULL, [isdashboards] [bit] NOT NULL, [iscustomobjectdata] [bit] NOT NULL, [sessioncols] [nvarchar](max) NULL, [dashboardcols] [nvarchar](max) NULL, [datecreated] [datetime] NULL, [advanced] [nvarchar](max) NULL, [type] [nvarchar](50) NULL, [isadvanced] [bit] NULL, [outputoptions] [nvarchar](max) NULL, CONSTRAINT [PK_BPADataPipelineOutputConfig] PRIMARY KEY CLUSTERED (id) ) CREATE INDEX [Index_BPADataPipelineOutputConfig_Name] ON [BPADataPipelineOutputConfig] ([name]) insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''311'', getutcdate(), ''db_upgradeR311.sql'', ''Add BPADataPipelineOutputConfig table'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='312') begin exec('alter table BPADataPipelineProcessConfig add iscustom bit NOT NULL default 0; insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''312'', getutcdate(), ''db_upgradeR312.sql'', ''Add iscustom column to BPADataPipelineProcessConfig table'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='313') begin exec('IF NOT EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.columns WHERE table_name = ''BPAPublicHoliday'' and column_name = ''excludesaturday'') BEGIN ALTER TABLE BPAPublicHoliday ADD excludesaturday BIT NULL; END ')exec('')exec('UPDATE h SET h.excludesaturday = 1 FROM BPAPublicHoliday h left join BPAPublicHolidayGroupMember m on m.publicholidayid = h.id left join BPAPublicHolidayGroup g on m.publicholidaygroupid = g.id WHERE g.[Name] = ''Hong Kong''; UPDATE h SET h.excludesaturday = 0 FROM BPAPublicHoliday h left join BPAPublicHolidayGroupMember m on m.publicholidayid = h.id left join BPAPublicHolidayGroup g on m.publicholidaygroupid = g.id WHERE g.[Name] IS NULL OR g.[Name] <> ''Hong Kong''; ALTER TABLE BPAPublicHoliday ALTER COLUMN excludesaturday bit NOT NULL; UPDATE h SET h.excludesaturday = 1 FROM BPAPublicHoliday h left join BPAPublicHolidayGroupMember m on m.publicholidayid = h.id left join BPAPublicHolidayGroup g on m.publicholidaygroupid = g.id WHERE g.[Name] = ''Japan''; IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N''BPAPublicHolidayShiftDayTypes'') BEGIN CREATE TABLE BPAPublicHolidayShiftDayTypes ( [id] int not null, [name] varchar(256) not null, CONSTRAINT PK_BPAPublicHolidayShiftDayTypes PRIMARY KEY ([id]), CONSTRAINT IX_BPAPublicHolidayShiftDayTypes_Name UNIQUE ([name]) ) END IF NOT EXISTS (SELECT 1 FROM [BPAPublicHolidayShiftDayTypes] WHERE [Name] = ''ShiftForward'') BEGIN INSERT INTO [BPAPublicHolidayShiftDayTypes] ([id], [name]) VALUES (1, ''ShiftForward''); END ')exec('')exec('IF NOT EXISTS (SELECT 1 FROM [BPAPublicHolidayShiftDayTypes] WHERE [Name] = ''ShiftBackwardOrForward'') BEGIN INSERT INTO [BPAPublicHolidayShiftDayTypes] ([id], [name]) VALUES (2, ''ShiftBackwardOrForward''); END ')exec('')exec('IF NOT EXISTS ( select 1 from INFORMATION_SCHEMA.columns where table_name = ''BPAPublicHoliday'' and column_name = ''shiftdaytypeid'') BEGIN ALTER TABLE BPAPublicHoliday add shiftdaytypeid int NULL; END ')exec('')exec('IF(OBJECT_ID(''FK_BPAPublicHoliday_BPAPublicHolidayShiftDayTypes'', ''F'') IS NULL) ALTER TABLE [BPAPublicHoliday] WITH CHECK ADD CONSTRAINT [FK_BPAPublicHoliday_BPAPublicHolidayShiftDayTypes] FOREIGN KEY(shiftdaytypeid) REFERENCES [BPAPublicHolidayShiftDayTypes]([id]); UPDATE h SET h.shiftdaytypeid = 1 FROM BPAPublicHoliday h left join BPAPublicHolidayGroupMember m on m.publicholidayid = h.id left join BPAPublicHolidayGroup g on m.publicholidaygroupid = g.id WHERE g.[name] IS NULL OR g.[name] <> ''USA''; UPDATE h SET h.shiftdaytypeid = 2 FROM BPAPublicHoliday h left join BPAPublicHolidayGroupMember m on m.publicholidayid = h.id left join BPAPublicHolidayGroup g on m.publicholidaygroupid = g.id WHERE g.[name] = ''USA''; ALTER TABLE BPAPublicHoliday ALTER COLUMN shiftdaytypeid int NOT NULL; UPDATE BPAPublicHoliday SET dd = null, dayofweek = 1, nthofmonth = 2 WHERE [name] = ''Columbus Day''; DELETE hgm FROM BPAPublicHolidayGroupMember hgm INNER JOIN BPAPublicHolidayGroup hg on hgm.publicholidaygroupid = hg.id INNER JOIN BPAPublicHoliday h on hgm.publicholidayid = h.id WHERE hg.[name] = ''China'' and h.[name] = ''National Day Golden Week holiday''; DELETE FROM BPAPublicHoliday WHERE [name] = ''National Day Golden Week holiday''; insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''313'', getutcdate(), ''db_upgradeR313.sql'', ''Add additional holiday related columns to handle new countries'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='314') begin exec('IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = ''P'' AND object_id = OBJECT_ID(''usp_CreateInterimQueueSnapshot'')) BEGIN EXEC(N''create procedure usp_CreateInterimQueueSnapshot as begin set nocount on; end;'') END ')exec('')exec('IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = ''P'' AND object_id = OBJECT_ID(''usp_CreateFirstQueueSnapshot'')) BEGIN EXEC(N''create procedure usp_CreateFirstQueueSnapshot as begin set nocount on; end;'') END ')exec('')exec('IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = ''P'' AND object_id = OBJECT_ID(''usp_CreateNextQueueSnapshot'')) BEGIN EXEC(N''create procedure usp_CreateNextQueueSnapshot as begin set nocount on; end;'') END ')exec('')exec('IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = ''P'' AND object_id = OBJECT_ID(''usp_CalculateQueueTrends'')) BEGIN EXEC(N''create procedure usp_CalculateQueueTrends as begin set nocount on; end;'') END ')exec('')exec('IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = ''TF'' AND object_id = OBJECT_ID(''ufn_GetQueueEvents'')) BEGIN EXEC(N''create function ufn_GetQueueEvents () returns @summary table (queueident int) as begin return; end;'') END ')exec('')exec('GRANT EXECUTE ON OBJECT::usp_CreateInterimQueueSnapshot TO bpa_ExecuteSP_System; ')exec('')exec('GRANT EXECUTE ON OBJECT::usp_CreateFirstQueueSnapshot TO bpa_ExecuteSP_System; ')exec('')exec('GRANT EXECUTE ON OBJECT::usp_CreateNextQueueSnapshot TO bpa_ExecuteSP_System; ')exec('')exec('GRANT EXECUTE ON OBJECT::usp_CalculateQueueTrends TO bpa_ExecuteSP_System; ')exec('')exec('alter function ufn_GetQueueEvents ( @queueIdent int, @fromDatetime datetime, @toDatetime datetime) returns @summary table( queueIdent int, totalItems int, itemsPending int, itemsCompleted int, itemsReferred int, createdSinceLast int, completedSinceLast int, referredSinceLast int, totalWorktimeCompleted bigint, totalWorktimeReferred bigint, totalIdletime bigint) as begin declare @itemEvents table ( queueIdent int, created int, completed int, referred int, deletedPending int, deletedCompleted int, deletedReferred int, completedWorktime bigint, referredWorktime bigint, finishedElapsedTime bigint) insert into @itemEvents (queueIdent, created, completed, referred, deletedPending, deletedCompleted, deletedReferred, completedWorktime, referredWorktime, finishedElapsedTime) select @queueIdent, ISNULL(SUM(case when eventid = 1 then 1 else 0 end), 0), ISNULL(SUM(case when eventid = 5 then 1 else 0 end), 0), ISNULL(SUM(case when eventid = 6 then 1 else 0 end), 0), ISNULL(SUM(case when (eventid = 7 and statewhendeleted = 1) then 1 else 0 end), 0), ISNULL(SUM(case when (eventid = 7 and statewhendeleted = 4) then 1 else 0 end), 0), ISNULL(SUM(case when (eventid = 7 and statewhendeleted = 5) then 1 else 0 end), 0), ISNULL(SUM(case when eventid = 5 then worktime else 0 end), 0), ISNULL(SUM(case when eventid = 6 then worktime else 0 end), 0), ISNULL(SUM(case when (eventid = 5 or eventid = 6) then CAST(elapsedtime as bigint) else 0 end), 0) from BPMIProductivityShadow where queueident = @queueIdent and eventid in (1, 5, 6, 7) and eventdatetime > @fromDatetime and eventdatetime <= @toDatetime; insert into @summary (queueIdent, totalItems, itemsPending, itemsCompleted, itemsReferred, createdSinceLast, completedSinceLast, referredSinceLast, totalWorktimeCompleted, totalWorktimeReferred, totalIdletime) select @queueIdent, created - (deletedPending + deletedCompleted + deletedReferred), created - (completed + referred + deletedPending), completed - deletedCompleted, referred - deletedReferred, created, completed, referred, completedWorktime, referredWorktime, finishedElapsedTime - completedWorktime - referredWorktime from @itemEvents; return; end ')exec('')exec('alter procedure usp_TriggerQueueSnapshot as declare @triggers table ( queueIdent int, snapshotId bigint, eventType int, snapshotDate datetimeoffset, snapshotDateUtc datetime, midnightUtc datetime) declare @regularSnapshot int = 1; declare @interimSnapshot int = 2; declare @trendCalculation int = 4; insert into @triggers select queueIdent, snapshotId, eventType, snapshotdate, snapshotdateutc, midnightutc from BPMISnapshotTrigger where snapshotdateutc <= GETUTCDATE() order by snapshotdate asc; declare @queueIdent int, @snapshotId bigint, @eventType int; declare @snapshotDate datetimeoffset, @midnightUtc datetime, @snapshotDateUtc datetime; declare @result int, @lockName as varchar(255); set transaction isolation level snapshot; while exists (select 1 from @triggers) begin select top 1 @queueIdent = queueident, @snapshotId = snapshotId, @eventType = eventType, @snapshotDate = snapshotDate, @snapshotDateUtc = snapshotDateUtc, @midnightUtc = midnightUtc from @triggers order by snapshotDate asc; begin try begin transaction; set @lockName = ''QueueSnapshot:'' + CAST(@queueIdent as varchar); exec @result = sp_getapplock @Resource=@lockName, @LockMode=''Exclusive'', @LockOwner=''Transaction'', @LockTimeout=100; if @result < 0 begin rollback transaction; delete from @triggers where queueIdent = @queueIdent and snapshotId = @snapshotId; continue; end if (@eventType & @regularSnapshot) = @regularSnapshot begin declare @lastSnapshotId bigint; select @lastSnapshotId = lastsnapshotid from BPAWorkQueue where ident = @queueIdent; if @lastSnapshotId is null exec usp_CreateFirstQueueSnapshot @queueIdent, @snapshotId, @snapshotDate, @snapshotDateUtc, @midnightUtc; else exec usp_CreateNextQueueSnapshot @queueIdent, @snapshotId, @snapshotDate, @snapshotDateUtc, @midnightUtc; end if (@eventType & @interimSnapshot) = @interimSnapshot begin exec usp_CreateInterimQueueSnapshot @queueIdent, @snapshotDate, @snapshotId; end if (@eventType & @trendCalculation) = @trendCalculation begin exec usp_CalculateQueueTrends @queueIdent, @snapshotDate, @snapshotId; end delete from BPMISnapshotTrigger where queueident = @queueIdent and snapshotId = @snapshotId; exec sp_releaseapplock @Resource=@lockName; commit transaction; end try begin catch rollback transaction; end catch delete from @triggers where queueIdent = @queueIdent and snapshotId = @snapshotId; end ')exec('')exec('alter procedure usp_CreateFirstQueueSnapshot @queueIdent int, @snapshotId bigint, @snapshotDate datetimeoffset, @snapshotDateUtc datetime, @midnightUtc datetime as declare @itemSummary table ( queueIdent int, pending int, completed int, referred int) declare @addedSince table ( queueIdent int, newSinceMidnight int, newLast24Hours int) insert into @itemSummary (queueIdent, pending, completed, referred) select @queueIdent, ISNULL(SUM(case when finished is null then 1 else 0 end), 0), ISNULL(SUM(case when completed is not null then 1 else 0 end), 0), ISNULL(SUM(case when exception is not null then 1 else 0 end), 0) from BPAWorkQueueItem where queueident = @queueIdent; declare @24HoursAgoUtc datetime = DATEADD(hour, -24, @snapshotDateUtc); insert into @addedSince select @queueIdent, ISNULL(SUM(case when (eventid = 1 and eventdatetime > @midnightUtc) then 1 else 0 end), 0), ISNULL(SUM(case when eventid = 1 then 1 else 0 end), 0) from BPMIProductivityShadow where queueident = @queueIdent and eventid = 1 and eventdatetime > @24HoursAgoUtc and eventdatetime <= @snapshotDateUtc; insert into BPMIQueueSnapshot (snapshotid, queueident, snapshotdate, totalitems, itemspending, itemscompleted, itemsreferred, newitemsdelta, completeditemsdelta, referreditemsdelta, totalworktimecompleted, totalworktimereferred, totalidletime, totalnewsincemidnight, totalnewlast24hours, averagecompletedworktime, averagereferredworktime, averageidletime) select @snapshotId, @queueIdent, @snapshotDate, summary.pending + summary.completed + summary.referred, summary.pending, summary.completed, summary.referred, 0, 0, 0, 0, 0, 0, ISNULL(added.newSinceMidnight, 0), ISNULL(added.newLast24Hours, 0), 0, 0, 0 from @itemSummary summary inner join @addedSince added on added.queueident = summary.queueident; update BPAWorkQueue set lastsnapshotid = @snapshotId where ident = @queueIdent; ')exec('')exec('alter procedure usp_CreateInterimQueueSnapshot @queueIdent int, @snapshotDate datetimeoffset, @snapshotId BIGINT as declare @snapshotDateUtc datetime = CONVERT(datetime, DATEADD(minute, -DATEPART(TzOffset, @snapshotDate), @snapshotDate)) if not exists (select queueident from BPMIQueueInterimSnapshot where queueident = @queueIdent) begin insert into BPMIQueueInterimSnapshot (queueident, snapshotdate, totalitems, itemspending, itemscompleted, itemsreferred, newitemsdelta, completeditemsdelta, referreditemsdelta, totalworktimecompleted, totalworktimereferred, totalidletime) select @queueIdent, @snapshotDate, totalItems, itemsPending, itemsCompleted, itemsReferred, createdSinceLast, completedSinceLast, referredSinceLast, totalWorktimeCompleted, totalWorktimeReferred, totalIdletime from ufn_GetQueueEvents(@queueIdent, DATEADD(hour, -24, @snapshotDateUtc), @snapshotDateUtc); end else begin update interim set interim.snapshotdate = @snapshotDate, interim.totalitems = interim.totalitems + deltas.totalItems, interim.itemspending = interim.itemspending + deltas.itemsPending, interim.itemscompleted = interim.itemscompleted + deltas.itemsCompleted, interim.itemsreferred = interim.itemsreferred + deltas.itemsReferred, interim.newitemsdelta = interim.newitemsdelta + deltas.createdSinceLast, interim.completeditemsdelta = interim.completeditemsdelta + deltas.completedSinceLast, interim.referreditemsdelta = interim.referreditemsdelta + deltas.referredSinceLast, interim.totalworktimecompleted = interim.totalworktimecompleted + deltas.totalWorktimeCompleted, interim.totalworktimereferred = interim.totalworktimereferred + deltas.totalWorktimeReferred, interim.totalidletime = interim.totalidletime + deltas.totalIdletime from BPMIQueueInterimSnapshot interim inner join ufn_GetQueueEvents(@queueIdent, DATEADD(hour, -24, @snapshotDateUtc), @snapshotDateUtc) deltas on deltas.queueIdent = interim.queueident where interim.queueident = @queueIdent; end UPDATE BPAWorkQueue SET lastsnapshotid = @snapshotId WHERE ident = @queueIdent; ')exec('')exec('alter procedure usp_CreateNextQueueSnapshot @queueIdent int, @snapshotId bigint, @snapshotDate datetimeoffset, @snapshotDateUtc datetime, @midnightUtc datetime as declare @previousSnapshot table ( queueIdent int, snapshotDate datetimeoffset, allItems int, pendingItems int, completedItems int, referredItems int) declare @InterimSnapshot table ( queueIdent int, snapshotDate datetimeoffset, allItems int, pendingItems int, completedItems int, referredItems int, createdSinceLast int, completedSinceLast int, referredSinceLast int, completedWorktime bigint, referredWorktime bigint, idleTime bigint) declare @addedSince table ( queueIdent int, createdSinceMidnight int, createdInLast24Hours int) insert into @previousSnapshot (queueIdent, snapshotDate, allItems, pendingItems, completedItems, referredItems) select top 1 @queueIdent, snapshotdate, totalitems, itemspending, itemscompleted, itemsreferred from BPMIQueueSnapshot where queueident = @queueIdent order by id desc; insert into @InterimSnapshot (queueIdent, snapshotDate, allItems, pendingItems, completedItems, referredItems, createdSinceLast, completedSinceLast, referredSinceLast, completedWorktime, referredWorktime, idleTime) select top 1 @queueIdent, snapshotdate, totalitems, itemspending, itemscompleted, itemsreferred, newitemsdelta, completeditemsdelta, referreditemsdelta, totalworktimecompleted, totalworktimereferred, totalidletime from BPMIQueueInterimSnapshot where queueident = @queueIdent order by queueident; declare @24HoursAgoUtc datetime = DATEADD(hour, -24, @snapshotDateUtc); declare @lastSnapshotDate datetimeoffset; select @lastSnapshotDate = ISNULL(interim.snapshotDate, previous.snapshotDate) from @previousSnapshot previous left join @InterimSnapshot interim on interim.queueIdent = previous.queueIdent; declare @lastSnapshotDateUtc datetime; set @lastSnapshotDateUtc = CONVERT(datetime, DATEADD(minute, -DATEPART(TzOffset, @lastSnapshotDate), @lastSnapshotDate)); insert into @addedSince (queueIdent, createdSinceMidnight, createdInLast24Hours) select @queueIdent, ISNULL(SUM(case when (eventid = 1 and eventdatetime > @midnightUtc) then 1 else 0 end), 0), ISNULL(SUM(case when (eventid = 1 and eventdatetime > @24HoursAgoUtc) then 1 else 0 end), 0) from BPMIProductivityShadow where queueident = @queueIdent and eventid = 1 and eventdatetime > @24HoursAgoUtc and eventdatetime <= @snapshotDateUtc; insert into BPMIQueueSnapshot (snapshotid, queueident, snapshotdate, totalitems, itemspending, itemscompleted, itemsreferred, newitemsdelta, completeditemsdelta, referreditemsdelta, totalworktimecompleted, totalworktimereferred, totalidletime, totalnewsincemidnight, totalnewlast24hours, averagecompletedworktime, averagereferredworktime, averageidletime) select @snapshotId, @queueIdent, @snapshotDate, previous.allItems + ISNULL(interim.allItems, 0) + deltas.totalItems, previous.pendingItems + ISNULL(interim.pendingItems, 0) + deltas.itemsPending, previous.completedItems + ISNULL(interim.completedItems, 0) + deltas.itemsCompleted, previous.referredItems + ISNULL(interim.referredItems, 0) + deltas.itemsReferred, ISNULL(interim.createdSinceLast, 0) + deltas.createdSinceLast, ISNULL(interim.completedSinceLast, 0) + deltas.completedSinceLast, ISNULL(interim.referredSinceLast, 0) + deltas.referredSinceLast, ISNULL(interim.completedWorktime, 0) + deltas.totalWorktimeCompleted, ISNULL(interim.referredWorktime, 0) + deltas.totalWorktimeReferred, ISNULL(interim.idleTime, 0) + deltas.totalIdletime, added.createdSinceMidnight, added.createdInLast24Hours, (case when ISNULL(interim.completedSinceLast, 0) + deltas.completedSinceLast > 0 then (ISNULL(interim.completedWorktime, 0) + deltas.totalWorktimeCompleted)/(ISNULL(interim.completedSinceLast, 0) + deltas.completedSinceLast) else 0 end), (case when ISNULL(interim.referredSinceLast, 0) + deltas.referredSinceLast > 0 then (ISNULL(interim.referredWorktime, 0) + deltas.totalWorktimeReferred)/(ISNULL(interim.referredSinceLast, 0) + deltas.referredSinceLast) else 0 end), (case when ISNULL(interim.completedSinceLast, 0) + ISNULL(interim.referredSinceLast, 0) + deltas.completedSinceLast + deltas.referredSinceLast > 0 then (ISNULL(interim.idleTime, 0) + deltas.totalIdletime)/(ISNULL(interim.completedSinceLast, 0) + ISNULL(interim.referredSinceLast, 0) + deltas.completedSinceLast + deltas.referredSinceLast) else 0 end) from @previousSnapshot previous left join @InterimSnapshot interim on interim.queueIdent = previous.queueIdent inner join @addedSince added on added.queueident = previous.queueident inner join ufn_GetQueueEvents(@queueIdent, @lastSnapshotDateUtc, @snapshotDateUtc) deltas on deltas.queueIdent = previous.queueIdent; update BPAWorkQueue set lastsnapshotid = @snapshotId where ident = @queueIdent; delete from BPMIQueueInterimSnapshot where queueident = @queueIdent; ')exec('')exec('alter procedure usp_CalculateQueueTrends @queueIdent int, @snapshotDate date, @snapshotId BIGINT as declare @trendDate date = CAST(DATEADD(day, -1, @snapshotDate) as date); delete from BPMIQueueTrend where queueident = @queueIdent; insert into BPMIQueueTrend (snapshottimeofdaysecs, queueident, trendid, averagetotalitems, averageitemspending, averageitemscompleted, averageitemsreferred, averagenewitemsdelta, averagecompleteditemsdelta, averagereferreditemsdelta, averagetotalworktimecompleted, averagetotalworktimereferred, averagetotalidletime, averagetotalnewsincemidnight, averagetotalnewlast24hours, averageaveragecompletedworktime, averageaveragereferredworktime, averageaverageidletime) select configuration.timeofdaysecs, snapshots.queueident, 1, AVG(snapshots.totalitems), AVG(snapshots.itemspending), AVG(snapshots.itemscompleted), AVG(snapshots.itemsreferred), AVG(snapshots.newitemsdelta), AVG(snapshots.completeditemsdelta), AVG(snapshots.referreditemsdelta), AVG(snapshots.totalworktimecompleted), AVG(snapshots.totalworktimereferred), AVG(snapshots.totalidletime), AVG(snapshots.totalnewsincemidnight), AVG(snapshots.totalnewlast24hours), AVG(snapshots.averagecompletedworktime), AVG(snapshots.averagereferredworktime), AVG(snapshots.averageidletime) from BPMIConfiguredSnapshot configuration inner join BPMIQueueSnapshot snapshots on snapshots.snapshotid = configuration.snapshotid and snapshots.queueident = configuration.queueident where configuration.queueident = @queueIdent and CAST(snapshots.snapshotdate as date) > CAST(DATEADD(day, -7, @trendDate) as date) and CAST(snapshots.snapshotdate as date) <= @trendDate group by configuration.timeofdaysecs, snapshots.queueident insert into BPMIQueueTrend (snapshottimeofdaysecs, queueident, trendid, averagetotalitems, averageitemspending, averageitemscompleted, averageitemsreferred, averagenewitemsdelta, averagecompleteditemsdelta, averagereferreditemsdelta, averagetotalworktimecompleted, averagetotalworktimereferred, averagetotalidletime, averagetotalnewsincemidnight, averagetotalnewlast24hours, averageaveragecompletedworktime, averageaveragereferredworktime, averageaverageidletime) select configuration.timeofdaysecs, snapshots.queueident, 2, AVG(snapshots.totalitems), AVG(snapshots.itemspending), AVG(snapshots.itemscompleted), AVG(snapshots.itemsreferred), AVG(snapshots.newitemsdelta), AVG(snapshots.completeditemsdelta), AVG(snapshots.referreditemsdelta), AVG(snapshots.totalworktimecompleted), AVG(snapshots.totalworktimereferred), AVG(snapshots.totalidletime), AVG(snapshots.totalnewsincemidnight), AVG(snapshots.totalnewlast24hours), AVG(snapshots.averagecompletedworktime), AVG(snapshots.averagereferredworktime), AVG(snapshots.averageidletime) from BPMIConfiguredSnapshot configuration inner join BPMIQueueSnapshot snapshots on snapshots.snapshotid = configuration.snapshotid and snapshots.queueident = configuration.queueident where configuration.queueident = @queueIdent and CAST(snapshots.snapshotdate as date) > CAST(DATEADD(day, -28, @trendDate) as date) and CAST(snapshots.snapshotdate as date) <= @trendDate group by configuration.timeofdaysecs, snapshots.queueident insert into BPMIQueueTrend (snapshottimeofdaysecs, queueident, trendid, averagetotalitems, averageitemspending, averageitemscompleted, averageitemsreferred, averagenewitemsdelta, averagecompleteditemsdelta, averagereferreditemsdelta, averagetotalworktimecompleted, averagetotalworktimereferred, averagetotalidletime, averagetotalnewsincemidnight, averagetotalnewlast24hours, averageaveragecompletedworktime, averageaveragereferredworktime, averageaverageidletime) select configuration.timeofdaysecs, snapshots.queueident, 3, AVG(snapshots.totalitems), AVG(snapshots.itemspending), AVG(snapshots.itemscompleted), AVG(snapshots.itemsreferred), AVG(snapshots.newitemsdelta), AVG(snapshots.completeditemsdelta), AVG(snapshots.referreditemsdelta), AVG(snapshots.totalworktimecompleted), AVG(snapshots.totalworktimereferred), AVG(snapshots.totalidletime), AVG(snapshots.totalnewsincemidnight), AVG(snapshots.totalnewlast24hours), AVG(snapshots.averagecompletedworktime), AVG(snapshots.averagereferredworktime), AVG(snapshots.averageidletime) from BPMIConfiguredSnapshot configuration inner join BPMIQueueSnapshot snapshots on snapshots.snapshotid = configuration.snapshotid and snapshots.queueident = configuration.queueident where configuration.queueident = @queueIdent and CAST(snapshots.snapshotdate as date) > CAST(DATEADD(day, -29, @snapshotDate) as date) and CAST(snapshots.snapshotdate as date) < @snapshotDate and DATEPART(weekday, snapshots.snapshotdate) = DATEPART(weekday, @snapshotDate) group by configuration.timeofdaysecs, snapshots.queueident delete from BPMIQueueSnapshot where queueident = @queueIdent and snapshotdate < DATEADD(day, -28, @trendDate); UPDATE BPAWorkQueue SET lastsnapshotid = @snapshotId WHERE ident = @queueIdent; ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''314'', getutcdate(), ''db_upgradeR314.sql'', ''Create stored procedures for work queue analysis'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='315') begin exec('IF DATABASE_PRINCIPAL_ID(''BPA_DataGatewaysEngine'') IS NULL EXEC(N''CREATE ROLE BPA_DataGatewaysEngine''); ')exec('')exec('GRANT DELETE ON [BPADataPipelineInput] TO BPA_DataGatewaysEngine ')exec('')exec('GRANT SELECT ON [BPADataPipelineInput] TO BPA_DataGatewaysEngine ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''315'', getutcdate(), ''db_upgradeR315.sql'', ''Create BPA_DataGatewaysEngine Role'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='316') begin exec('DECLARE @WorkQueueAnalysisPreference VARCHAR(100) = ''EnvironmentLockTimeExpiry.WorkQueueAnalysis.InSeconds''; DECLARE @DataGatewaysPreference VARCHAR(100) = ''EnvironmentLockTimeExpiry.DataGateways.InSeconds''; DECLARE @MIReportingPreference VARCHAR(100) = ''EnvironmentLockTimeExpiry.MIReporting.InSeconds''; DECLARE @DefaultExpiryTimeInSeconds INT = 600; DECLARE @prefId INT; IF NOT EXISTS (SELECT 1 FROM BPAPref WHERE [name] = @WorkQueueAnalysisPreference AND userid IS NULL) BEGIN INSERT INTO BPAPref ([name]) VALUES (@WorkQueueAnalysisPreference); END SET @prefId = (SELECT TOP 1 id FROM BPAPref WHERE [name] = @WorkQueueAnalysisPreference AND userid IS NULL); IF NOT EXISTS (SELECT 1 FROM BPAIntegerPref WHERE prefid = @prefId) BEGIN INSERT INTO BPAIntegerPref (prefid, [value]) VALUES (@prefId, @DefaultExpiryTimeInSeconds); END IF NOT EXISTS (SELECT 1 FROM BPAPref WHERE [name] = @DataGatewaysPreference AND userid IS NULL) BEGIN INSERT INTO BPAPref ([name]) VALUES (@DataGatewaysPreference); END SET @prefId = (SELECT TOP 1 id FROM BPAPref WHERE [name] = @DataGatewaysPreference AND userid IS NULL); IF NOT EXISTS (SELECT 1 FROM BPAIntegerPref WHERE prefid = @prefId) BEGIN INSERT INTO BPAIntegerPref (prefid, [value]) VALUES (@prefId, @DefaultExpiryTimeInSeconds); END IF NOT EXISTS (SELECT 1 FROM BPAPref WHERE [name] = @MIReportingPreference AND userid IS NULL) BEGIN INSERT INTO BPAPref ([name]) VALUES (@MIReportingPreference); END SET @prefId = (SELECT TOP 1 id FROM BPAPref WHERE [name] = @MIReportingPreference AND userid IS NULL); IF NOT EXISTS (SELECT 1 FROM BPAIntegerPref WHERE prefid = @prefId) BEGIN INSERT INTO BPAIntegerPref (prefid, [value]) VALUES (@prefId, @DefaultExpiryTimeInSeconds); END INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''316'', getutcdate(), ''db_upgradeR316.sql'', ''Add environment lock time expiry preference values to BPAPref table.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='317') begin exec('IF not exists (select * from sys.objects where type = ''P'' and name = ''BPDS_QueueSnapshotAgainstTrend'') EXEC(N''create procedure BPDS_QueueSnapshotAgainstTrend as begin set nocount on; end''); ')exec('')exec('ALTER procedure [BPDS_QueueSnapshotAgainstTrend] @QueueName NVARCHAR(255) = NULL, @TrendId INT = 1, @ColumnIdentifier INT = 1, @TimeRangeStartTime VARCHAR(8) = NULL, @TimeRangeEndTime VARCHAR(8) = NULL AS IF @QueueName IS NULL RAISERROR(''@QueueName must be specified.'', 11, 1); IF @TrendId < 1 or @TrendId > 3 RAISERROR(''@Trend must be between 1 and 3.'', 11, 1); IF @ColumnIdentifier < 1 or @ColumnIdentifier > 15 RAISERROR(''@ColumnIdentifier must be between 1 and 15.'', 11, 1); DECLARE @ColumnName NVARCHAR(255) = NULL; DECLARE @QueueIdent INT = -1; DECLARE @Sql NVARCHAR(2000); DECLARE @TrendDataNotAvailable BIT DECLARE @DontUseTimeRange BIT = 1; DECLARE @TimeRangeStartTimeConverted TIME(7); DECLARE @TimeRangeEndTimeConverted TIME(7); DECLARE @OffsetMinutes INT = 0 DECLARE @TodaysStartDateTime DATETIME; DECLARE @DayOfWeek INT; IF @TimeRangeStartTime IS NOT NULL AND @TimeRangeEndTime IS NOT NULL BEGIN SET @TimeRangeStartTimeConverted = CAST(@TimeRangeStartTime AS TIME(7)) SET @TimeRangeEndTimeConverted = CAST(@TimeRangeEndTime AS TIME(7)) SET @DontUseTimeRange = 0; END SELECT TOP 1 @QueueIdent = BPAWorkQueue.ident, @TrendDataNotAvailable = CASE WHEN BPMIQueueTrend.id IS NULL THEN 1 ELSE 0 END FROM BPAWorkQueue LEFT JOIN BPMIQueueTrend ON BPAWorkQueue.ident = BPMIQueueTrend.queueident AND BPMIQueueTrend.trendid = @TrendId WHERE BPAWorkQueue.[name] = @QueueName; IF @QueueIdent = -1 BEGIN RAISERROR(''@QueueName does not exist.'', 11, 1); RETURN; END; IF @TrendDataNotAvailable = 1 BEGIN RAISERROR(''Trend data not available.'', 11, 1); RETURN; END; SELECT top 1 @OffsetMinutes = datepart(TZoffset, snapshotdate) FROM BPMIQueueSnapshot WHERE queueident = @QueueIdent ORDER BY snapshotdate DESC; SET @TodaysStartDateTime = DATEADD(MI, @OffsetMinutes, GETUTCDATE()); SET @DayOfWeek = DATEPART(WEEKDAY, @TodaysStartDateTime) - 1 IF @DayOfWeek = 0 SET @DayOfWeek = 7 SET @ColumnName = CASE @ColumnIdentifier WHEN 1 THEN ''totalitems'' WHEN 2 THEN ''itemspending'' WHEN 3 THEN ''itemscompleted'' WHEN 4 THEN ''itemsreferred'' WHEN 5 THEN ''newitemsdelta'' WHEN 6 THEN ''completeditemsdelta'' WHEN 7 THEN ''referreditemsdelta'' WHEN 8 THEN ''totalworktimecompleted'' WHEN 9 THEN ''totalworktimereferred'' WHEN 10 THEN ''totalidletime'' WHEN 11 THEN ''totalnewsincemidnight'' WHEN 12 THEN ''totalnewlast24hours'' WHEN 13 THEN ''averagecompletedworktime'' WHEN 14 THEN ''averagereferredworktime'' WHEN 15 THEN ''averageidletime'' ELSE ''totalitems'' END; SET @Sql = ''SELECT [Time], [Trend Metric], [Current Metric] FROM (SELECT CONVERT(VARCHAR(5), DATEADD(SS, configuredsnapshot.timeofdaysecs, 0), 8) as [Time], trend.average'' + @ColumnName + '' as [Trend Metric], COALESCE(today.'' + @ColumnName + '', 0) as [Current Metric] FROM BPMIConfiguredSnapshot configuredsnapshot INNER JOIN BPMIQueueTrend trend ON trend.queueident = @QueueIdent AND trend.trendid = @TrendId AND trend.snapshottimeofdaysecs = configuredsnapshot.timeofdaysecs LEFT JOIN BPMIQueueSnapshot today ON today.snapshotid = configuredsnapshot.snapshotid AND CAST(today.snapshotdate as date) = CAST(@TodaysStartDateTime as date) WHERE configuredsnapshot.dayofweek = @DayOfWeek ) Results WHERE @DontUseTimeRange = 1 OR (@TimeRangeStartTimeConverted <= Results.Time AND @TimeRangeEndTimeConverted >= Results.Time)''; EXEC sp_executesql @Sql, N''@QueueIdent INT, @TrendId INT, @DontUseTimeRange BIT, @TimeRangeStartTimeConverted TIME(7), @TimeRangeEndTimeConverted TIME(7), @TodaysStartDateTime DATETIME, @DayOfWeek INT'', @QueueIdent, @TrendId, @DontUseTimeRange, @TimeRangeStartTimeConverted, @TimeRangeEndTimeConverted, @TodaysStartDateTime, @DayOfWeek; RETURN; ')exec('')exec('GRANT EXECUTE ON OBJECT::BPDS_QueueSnapshotAgainstTrend TO bpa_ExecuteSP_DataSource_bpSystem; ')exec('')exec('INSERT INTO BPATileDataSources(spname, tiletype, helppage) VALUES(''BPDS_QueueSnapshotAgainstTrend'', 1, ''QueueSnapshotAgainstTrend.htm''); INSERT INTO BPADBVersion VALUES ( ''317'', GETUTCDATE(), ''db_upgradeR317.sql UTC'', ''Create data source for comparison of todays queue against a trend'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='318') begin exec('IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[FK_BPMIConfiguredSnapshot_BPMISnapshotTrigger]'') AND parent_object_id = OBJECT_ID(N''[BPMISnapshotTrigger]'')) BEGIN ALTER TABLE [BPMISnapshotTrigger] WITH CHECK ADD CONSTRAINT [FK_BPMIConfiguredSnapshot_BPMISnapshotTrigger] FOREIGN KEY([snapshotid]) REFERENCES [BPMIConfiguredSnapshot] ([snapshotid]) ON DELETE CASCADE; END INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''318'', GETUTCDATE(), ''db_upgradeR318.sql'', ''Add FK restraint to BPMISnapshotTrigger table to link to BPMIConfiguredSnapshot.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='319') begin exec('if not exists (SELECT 1 FROM BPAStatus WHERE statusid = 8) BEGIN INSERT INTO BPAStatus(statusid, [type], [description]) VALUES (8, ''RUN'', ''Warning''); END INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''319'', GETUTCDATE(), ''db_upgradeR319sql'', ''Add missing Warning status to BPAStatus table.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='320') begin exec('CREATE TABLE [BPAScope]( [id] int IDENTITY NOT NULL CONSTRAINT [PK_BPAScope] PRIMARY KEY, [scope] nvarchar(255) NOT NULL) CREATE TABLE [BPAPermScope] ([id] int IDENTITY NOT NULL CONSTRAINT [PK_BPAPermScope] PRIMARY KEY, [permid] int NOT NULL CONSTRAINT [FK_BPAPermScope_BPAPerm] FOREIGN KEY REFERENCES BPAPerm(id), [scopeid] int NOT NULL CONSTRAINT [FK_BPAPermScope_BPAScope] FOREIGN KEY REFERENCES BPAScope(id)) INSERT INTO BPADBVersion( dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''320'', GETUTCDATE(), ''db_upgradeR320sql'', ''Add permission and scope tables.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='321') begin exec('ALTER VIEW [BPVGroupedResources] AS SELECT g.treeid AS treeid, (CASE WHEN r.[pool] IS NOT NULL THEN r.[pool] ELSE g.id END) AS groupid, g.name AS groupname, r.resourceid AS id, r.name AS name, r.attributeid AS attributes, CASE WHEN r.[pool] IS NOT NULL THEN 1 ELSE 0 END AS ispoolmember, 1 AS statusid, r.diagnostics, r.logtoeventlog FROM [BPAResource] r LEFT JOIN ( [BPAGroupResource] gr INNER JOIN BPAGroup g ON gr.groupid = g.id ) ON gr.memberid = r.resourceid WHERE attributeId & 8 = 0; ')exec('')exec('INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''321'', GETUTCDATE(), ''db_upgradeR321sql'', ''Add extra columns to BPVGroupedResources.'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='322') begin exec('alter table BPADataPipelineOutputConfig add iswqasnapshotdata bit not null default 0; ')exec('')exec('alter table BPMIQueueSnapshot add senttodatagateways bit not null default 0; ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''322'', getutcdate(), ''db_upgradeR322.sql'', ''Add WQA snap shot data flag columns'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='323') begin exec('ALTER TABLE [BPADataPipelineOutputConfig] ADD selecteddashboards nvarchar(max) ')exec('')exec('INSERT INTO BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) VALUES(''323'', GETUTCDATE(), ''db_upgradeR323.sql'', ''Add extra column to BPADataPipelineOutputConfig'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='324') begin exec('if not exists(select 1 from sys.columns where name = N''sendworkqueueanalysistodatagateways'' and object_id = object_id(N''BPADataPipelineSettings'')) begin alter table [BPADataPipelineSettings] add [sendworkqueueanalysistodatagateways] bit not null default 0 end ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''324'', getutcdate(), ''db_upgradeR324sql'', ''Add extra column to BPADataPipelineSettings.'', 0); ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='325') begin exec('if not exists (select * from BPAPref where [name] = ''SessionLogMaxAttributeXmlLength'' AND userid IS NULL) begin insert into BPAPref ([name]) values (''SessionLogMaxAttributeXmlLength'') end DECLARE @prefId INT = (select TOP 1 id from BPAPref where [name] = ''SessionLogMaxAttributeXmlLength'' AND userid IS NULL); if not exists (select * from BPAIntegerPref where prefid = @prefId) begin insert into BPAIntegerPref (prefid, [value]) values (@prefId, 2000000000) end if not exists (select * from BPADataTracker where dataname = ''Preferences'') begin insert into BPADataTracker (dataname, versionno) values (''Preferences'', 1) end insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''325'', getutcdate(), ''db_upgradeR325sql'', ''Stop archiving failing when attributeXML huge and when huge numbers of sessionlogs'', 0); ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='326') begin exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''326'', getutcdate(), ''db_upgradeR326.sql'', ''removed'', 0); ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='327') begin exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''327'', getutcdate(), ''db_upgradeR327.sql'', ''removed'', 0); ')exec('')exec('') end
if not exists (select 1 from BPADBVersion where dbversion='328') begin exec('update BPADashboard set name = name + ( select case when s.uniqueno = 1 then '''' else '' ('' + cast(uniqueno-1 as varchar) + '')'' end from ( select id, dashtype, name, row_number() over(partition by upper(rtrim(ltrim(name))) order by lastsent) as uniqueno from BPADashboard ) s where BPADashboard.id = s.id ) where dashtype = 2 create index IX_BPAAuditEvents_gTgtProcID on BPAAuditEvents (gTgtProcID) insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''328'', getutcdate(), ''db_upgradeR328.sql'', ''Rename published dashboards. Add index to BPAAuditEvents'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='329') begin exec('create table BPAUserExternalIdentity ( bpuserid uniqueidentifier not null constraint FK_BPAUserExternalIdentity_BPAUser foreign key references BPAUser (userid), idprovider nvarchar(10) not null, externalid nvarchar(254) not null ); ')exec('')exec('alter table BPAUserExternalIdentity add constraint UNQ_bpuserid_idprovider unique (bpuserid, idprovider); ')exec('')exec('create index IX_BPAUserExternalIdentity_idprovider_externalid on BPAUserExternalIdentity(idprovider, externalid) ')exec('')exec('alter table BPASysConfig add authenticationserverurl nvarchar(2083) null; ')exec('')exec('insert into BPADBVersion(dbversion, scriptrundate, scriptname, [description], timezoneoffset) values(''329'', getutcdate(), ''db_upgradeR329.sql'', ''Add table BPAUserExternalIdentity and add authenticationserverurl field to BPASysConfig'', 0); ') end
if not exists (select 1 from BPADBVersion where dbversion='330') begin exec('ALTER PROCEDURE [BPDS_QueueVolumesNow] @BPQueueName NVARCHAR(MAX) = NULL, @ExcludePending NVARCHAR(MAX) = ''False'', @ExcludeDeferred NVARCHAR(MAX) = ''False'', @ExcludeComplete NVARCHAR(MAX) = ''False'', @ExcludeExceptions NVARCHAR(MAX) = ''False'' AS IF @ExcludePending NOT IN(''True'', ''False'') RAISERROR(''@ExcludePending must be either True or False'', 11, 1); ELSE IF @ExcludeDeferred NOT IN(''True'', ''False'') RAISERROR(''@ExcludeDeferred must be either True or False'', 11, 1); ELSE IF @ExcludeComplete NOT IN(''True'', ''False'') RAISERROR(''@ExcludeComplete must be either True or False'', 11, 1); ELSE IF @ExcludeExceptions NOT IN(''True'', ''False'') RAISERROR(''@ExcludeExceptions must be either True or False'', 11, 1); ELSE IF @BPQueueName IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM BPAWorkQueue WHERE name = @BPQueueName ) BEGIN DECLARE @rtnMessage VARCHAR(500)= CONCAT(''@BPQueueName, provided queue ('', @BPQueueName, '') name does not exist''); RAISERROR(@rtnMessage, 11, 1); END; ELSE BEGIN DECLARE @ColumnNames NVARCHAR(MAX); SELECT @ColumnNames = ISNULL(@ColumnNames + '','', '''') + QUOTENAME(ItemStatus) FROM ( SELECT ''Pending'' AS ItemStatus WHERE @ExcludePending = ''False'' UNION SELECT ''Deferred'' AS ItemStatus WHERE @ExcludeDeferred = ''False'' UNION SELECT ''Complete'' AS ItemStatus WHERE @ExcludeComplete = ''False'' UNION SELECT ''Exceptions'' AS ItemStatus WHERE @ExcludeExceptions = ''False'' ) AS StatusNarrs; DECLARE @WhereClause NVARCHAR(MAX); SET @WhereClause = ISNULL('' and q.name = '''''' + @BPQueueName + '''''''', ''''); DECLARE @SQLQuery NVARCHAR(MAX); DECLARE @Params NVARCHAR(500); IF @BPQueueName IS NOT NULL BEGIN SET @SQLQuery = ''with results as ( select q.name, case when i.state = 1 then ''''Pending'''' when i.state = 3 then ''''Deferred'''' when i.state = 4 then ''''Complete'''' when i.state = 5 then ''''Exceptions'''' end as state, COUNT(*) as Number from BPAWorkQueue q inner join BPVWorkQueueItem i on i.queueident=q.ident where i.state in (1,3,4,5) AND q.name = @WhereParam group by q.name, i.state) select name, '' + @ColumnNames + '' from results pivot (SUM(Number) for state in ('' + @ColumnNames + '')) as number''; SET @params = N''@WhereParam nvarchar(max)''; EXECUTE sp_executesql @SQLQuery, @Params, @WhereParam = @WhereClause; END; ELSE BEGIN SET @SQLQuery = ''with results as ( select q.name, case when i.state = 1 then ''''Pending'''' when i.state = 3 then ''''Deferred'''' when i.state = 4 then ''''Complete'''' when i.state = 5 then ''''Exceptions'''' end as state, COUNT(*) as Number from BPAWorkQueue q inner join BPVWorkQueueItem i on i.queueident=q.ident where i.state in (1,3,4,5) group by q.name, i.state) select name, '' + @ColumnNames + '' from results pivot (SUM(Number) for state in ('' + @ColumnNames + '')) as number''; EXECUTE sp_executesql @SQLQuery; END; END; return ')exec('')exec('ALTER PROCEDURE [BPDS_Exceptions] @BPQueueName NVARCHAR(MAX) = NULL, @NumberOfDays INT = 3 AS IF @BPQueueName IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM BPAWorkQueue WHERE name = @BPQueueName ) BEGIN DECLARE @rtnMessage VARCHAR(500)= CONCAT(''@BPQueueName, provided queue ('', @BPQueueName, '') name does not exist''); RAISERROR(@rtnMessage, 11, 1); END; IF @NumberOfDays < 1 OR @NumberOfDays > 31 RAISERROR(''@NumberOfDays must be between 1 and 31'', 11, 1); ELSE BEGIN DECLARE @ColumnName NVARCHAR(MAX); DECLARE @Query NVARCHAR(MAX); DECLARE @WhereClause NVARCHAR(MAX); DECLARE @Params NVARCHAR(500); DECLARE @dayVarchar NVARCHAR= CAST(@numberOfDays AS NVARCHAR); SET @WhereClause = ISNULL('' and q.name = '''''' + @BPQueueName + '''''''', ''''); SELECT @ColumnName = ISNULL(@ColumnName + '','', '''') + QUOTENAME(DATENAME(day, TheDate) + ''-'' + DATENAME(month, TheDate)) FROM ufn_GetReportDays(@NumberOfDays) ORDER BY TheDate; IF @BPQueueName IS NOT NULL BEGIN SET @Query = ''select name, '' + @ColumnName + '' from (select ISNULL(q.name, ''''<unknown>'''') as name, DATENAME(day, d.reportdate) + ''''-'''' + DATENAME(month, d.reportdate) as pivotdate, d.exceptioned from BPMIProductivityDaily d left join BPAWorkQueue q on d.queueident = q.ident where d.reportdate >= (select MIN(TheDate) from ufn_GetReportDays(@DaysParam)) and q.name = @WhereParam) as src pivot (sum(exceptioned) for pivotdate in ('' + @ColumnName + '')) as pvt''; SET @params = N''@WhereParam nvarchar(max), @DaysParam nvarchar''; EXECUTE sp_executesql @Query, @Params, @WhereParam = @WhereClause, @DaysParam = @dayVarchar; END; ELSE BEGIN SET @Query = ''select name, '' + @ColumnName + '' from (select ISNULL(q.name, ''''<unknown>'''') as name, DATENAME(day, d.reportdate) + ''''-'''' + DATENAME(month, d.reportdate) as pivotdate, d.exceptioned from BPMIProductivityDaily d left join BPAWorkQueue q on d.queueident = q.ident where d.reportdate >= (select MIN(TheDate) from ufn_GetReportDays(@DaysParam)) ) as src pivot (sum(exceptioned) for pivotdate in ('' + @ColumnName + '')) as pvt''; SET @params = N''@DaysParam nvarchar''; EXECUTE sp_executesql @Query, @Params, @DaysParam = @dayVarchar; END; END; return; ')exec('')exec('INSERT INTO BPADBVersion (dbversion, scriptrundate, scriptname, [description], timezoneoffset ) VALUES (''330'', GETUTCDATE(), ''db_upgradeR330.sql'', ''Modify dashboard stored procedures to use sp_executesql.'', 0 ); ') end
if not exists (select 1 from BPADBVersion where dbversion='332') begin exec('IF OBJECT_ID(''BPAPermScope'', ''U'') IS NOT NULL DROP TABLE BPAPermScope; IF OBJECT_ID(''BPAScope'', ''U'') IS NOT NULL DROP TABLE BPAScope; INSERT INTO BPADBVersion (dbversion, scriptrundate, scriptname, [description], timezoneoffset ) VALUES (''332'', GETUTCDATE(), ''db_upgradeR332.sql'', ''Removal of BPAPermScope and BPAScope for cleanup purposes.'', 0 ); ') end
if (select InstallInProgress from BPVScriptEnvironment) = 1 alter table BPASysConfig drop column InstallInProgress;